public RoslynCodeAnalysisHelper(IWpfTextView view, ITextDocument document, IVsTaskList tasks, DTE2 dte, SVsServiceProvider serviceProvider, IVsActivityLog log)
        {
            _view = view;
            _document = document;
            _text = new Adornment();
            _tasks = tasks;
            _serviceProvider = serviceProvider;
            _log = log;
            _dispatcher = Dispatcher.CurrentDispatcher;

            _adornmentLayer = view.GetAdornmentLayer(RoslynCodeAnalysisFactory.LayerName);

            _view.ViewportHeightChanged += SetAdornmentLocation;
            _view.ViewportWidthChanged += SetAdornmentLocation;

            _text.MouseUp += (s, e) => dte.ExecuteCommand("View.ErrorList");

            _timer = new Timer(750);
            _timer.Elapsed += (s, e) =>
            {
                _timer.Stop();
                System.Threading.Tasks.Task.Run(() =>
                {
                    _dispatcher.Invoke(new Action(() => Update(false)), DispatcherPriority.ApplicationIdle, null);
                });
            };
            _timer.Start();
        }
Example #2
0
        protected PackageLog(string source, IVsActivityLog activityLog)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            if (activityLog == null)
                throw new ArgumentNullException("activityLog");

            Source = source;
            ActivityLog = activityLog;
        }
Example #3
0
 public InterpreterLog([Import(typeof(SVsServiceProvider))]IServiceProvider provider) {
     _activityLog = (IVsActivityLog)provider.GetService(typeof(SVsActivityLog));
 }
        /// <summary>
        /// 包的初始化;这个方法将在包被选址后调用,所以你可以把所有
        /// 基于Visual Studio提供服务的初始化代码放在这儿。
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            ToolboxInitialized += new EventHandler(ToolboxItemPackage_ToolboxInitialized);
            this.ToolboxUpgraded += new EventHandler(ToolboxItemPackage_ToolboxUpgraded);
            // 初始化服务.
            vsActivityLog = GetService(typeof(SVsActivityLog)) as IVsActivityLog;
            vsToolbox2 = GetService(typeof(SVsToolbox)) as IVsToolbox2;

            LogEntry(__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION,
                string.Format("Entering initializer for: {0}", this.ToString()));

            // 添加工具箱项,如果它不存在.
            try
            {
                if (!VerifyToolboxTabExist())
                {
                    AddToolboxTab();
                }

                if (!VerifyToolboxItemExist())
                {
                    AddToolboxItem();
                }

            }
            catch (Exception ex)
            {
                LogEntry(__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR, ex.Message);
                LogEntry(__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR, ex.StackTrace);
            }
        }
 public static void LogWarning(this IVsActivityLog logger, string packageName, string message)
 {
     logger.LogEntry((UInt32)__ACTIVITYLOG_ENTRYTYPE.ALE_WARNING, packageName, message);
 }
Example #6
0
 public ActivityLogAdapter(IVsActivityLog log, string sourceName)
 {
     _log = log;
     _sourceName = sourceName;
 }
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override async Task InitializeAsync(CancellationToken token, IProgress <ServiceProgressData> progress)
        {
            try
            {
                _componentModel = await GetServiceAsync <SComponentModel, IComponentModel>();

                CredentialsStore = _componentModel.GetService <ICredentialsStore>();
                ExportProvider mefExportProvider = _componentModel.DefaultExportProvider;
                _shellUtilsLazy      = mefExportProvider.GetExport <IShellUtils>();
                _gcpOutputWindowLazy = mefExportProvider.GetExport <IGcpOutputWindow>();
                _processService      = mefExportProvider.GetExport <IProcessService>();
                _statusbarService    = mefExportProvider.GetExport <IStatusbarService>();
                _userPromptService   = mefExportProvider.GetExport <IUserPromptService>();
                _dataSourceFactory   = mefExportProvider.GetExport <IDataSourceFactory>();

                Dte = await GetServiceAsync <SDTE, DTE2>();

                // Remember the package.
                Instance = this;

                // Activity log utils, to aid in debugging.
                IVsActivityLog activityLog = await GetServiceAsync <SVsActivityLog, IVsActivityLog>();

                await activityLog.LogInfoAsync("Starting Google Cloud Tools.");

                // Register the command handlers.
                await Task.WhenAll(
                    CloudExplorerCommand.InitializeAsync(this, token),
                    ManageAccountsCommand.InitializeAsync(this, token),
                    PublishProjectMainMenuCommand.InitializeAsync(this, token),
                    PublishProjectContextMenuCommand.InitializeAsync(this, token),
                    LogsViewerToolWindowCommand.InitializeAsync(this, token),
                    GenerateConfigurationContextMenuCommand.InitializeAsync(this, token),
                    ErrorReportingToolWindowCommand.InitializeAsync(this, token));


                // Update the installation status of the package.
                await CheckInstallationStatusAsync();

                // Ensure the commands UI state is updated when the GCP project changes.
                CredentialsStore.CurrentProjectIdChanged += (o, e) => ShellUtils.InvalidateCommandsState();

                // With this setting we allow more concurrent connections from each HttpClient instance created
                // in the process. This will allow all GCP API services to have more concurrent connections with
                // GCP servers. The first benefit of this is that we can upload more concurrent files to GCS.
                ServicePointManager.DefaultConnectionLimit = MaximumConcurrentConnections;

                IVsRegisterUIFactories registerUIFactories =
                    await GetServiceAsync <SVsUIFactory, IVsRegisterUIFactories>();

                var controlFactory = _componentModel.GetService <GcpMenuBarControlFactory>();
                await registerUIFactories.RegisterUIFactoryAsync(controlFactory, token);
            }
            catch (Exception e)
            {
                IVsActivityLog activityLog = await GetServiceAsync <SVsActivityLog, IVsActivityLog>();

                await activityLog.LogErrorAsync(e.Message);

                await activityLog.LogErrorAsync(e.StackTrace);
            }
        }
Example #8
0
 public LogService(IThreadingContext threadingContext, IVsActivityLog activityLog)
     : base(threadingContext)
 {
     _activityLog = activityLog;
 }
Example #9
0
 public VsActivityLogger(SVsServiceProvider serviceProvider, IVsfTelemetry telemetry)
 {
     this.telemetry   = telemetry;
     this.activityLog = serviceProvider.GetService(typeof(SVsActivityLog)) as IVsActivityLog;
 }
Example #10
0
 internal static void Initialize(IVsActivityLog log)
 {
     mInstance = log;
 }
Example #11
0
 public ActivityLogger(IVsActivityLog log) {
     _log = log;
 }
Example #12
0
 internal static void Initialize(IVsActivityLog log)
 {
     mInstance = log;
 }
Example #13
0
 public PrigActivityLog(IVsActivityLog activityLog)
     : base("Prig", activityLog)
 { }
        public VisualStudioActivityLogAppender(IServiceProvider serviceProvider)
        {
            _log = serviceProvider.GetService(typeof(SVsActivityLog)) as IVsActivityLog;

            Source = typeof (VisualStudioActivityLogAppender).Name;
        }
Example #15
0
        protected override void Initialize()
        {
            // determine whether we're running the experimental instance.
            _isExperimental = false;
            string[] args = Environment.GetCommandLineArgs();
            if (args.Length >= 3 && args[2].Equals("exp", StringComparison.OrdinalIgnoreCase))
            {
                _isExperimental = true;
            }

            // get the product version
            IVsExtensionManager manager     = GetService(typeof(SVsExtensionManager)) as IVsExtensionManager;
            IInstalledExtension myExtension = manager.GetInstalledExtension(PackageId);

            if (myExtension != null)
            {
                ProductVersion = myExtension.Header.Version;
            }

            // Initialize NLog
            if (LogManager.Configuration == null)
            {
                string path = Path.Combine(SettingsDirectory, string.Format("{0}_NLog.config", PackageName));
                if (!File.Exists(path))
                {
                    // Get the template from resources and write it to the directory.
                    if (!Directory.Exists(SettingsDirectory))
                    {
                        Directory.CreateDirectory(SettingsDirectory);
                    }
                    File.WriteAllText(path, GetDefaultNLogConfigFileContents());
                }
                if (File.Exists(path))
                {
                    LogManager.Configuration = new XmlLoggingConfiguration(path);
                    // Register for changes to the config file
                    LogManager.ConfigurationChanged += LogManager_ConfigurationChanged;
                }
            }

            // Get the current logger now, since we have the configuration
            _logger = LogManager.GetCurrentClassLogger();
            _logger.Trace("VS arguments: [{0}]", string.Join(",", args));

            var componentManager = _compMgr = (IOleComponentManager)GetService(typeof(SOleComponentManager));

            OLECRINFO[] crinfo = new OLECRINFO[1];
            crinfo[0].cbSize            = (uint)Marshal.SizeOf(typeof(OLECRINFO));
            crinfo[0].grfcrf            = (uint)_OLECRF.olecrfNeedIdleTime;
            crinfo[0].grfcadvf          = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff;
            crinfo[0].uIdleTimeInterval = 0;
            ErrorHandler.ThrowOnFailure(componentManager.FRegisterComponent(this, crinfo, out _componentID));

            _activityLog = GetService(typeof(SVsActivityLog)) as IVsActivityLog;

            base.Initialize();
            Instance = this;

            _packageDTEEvents = ApplicationObject.Events.DTEEvents;
            _packageDTEEvents.OnBeginShutdown += OnBeginShutdown;
        }
 public VisualStudioActivityLogger(IVsActivityLog vsActivityLog)
 {
     _vsActivityLog = vsActivityLog;
 }
Example #17
0
 public InterpreterLog([Import(typeof(SVsServiceProvider))] IServiceProvider provider)
 {
     _activityLog = (IVsActivityLog)provider.GetService(typeof(SVsActivityLog));
 }
Example #18
0
        /// <summary>
        /// Default ctor
        /// </summary>
        /// <param name="package"></param>
        public SpriteContainer(AsyncPackage package)
        {
            _package = package;

            ThreadHelper.ThrowIfNotOnUIThread();
            var settingsManager = new ShellSettingsManager(ServiceProvider.GlobalProvider);

            _userSettingsStore = settingsManager.GetWritableSettingsStore(SettingsScope.UserSettings);

            InitializeComponent();

            this.Owner   = Application.Current.MainWindow;
            this.Topmost = false;

            #region Register event handlers
            if (package == null)
            {
                throw new ArgumentException("Package was null");
            }

            IVsActivityLog activityLog = package.GetServiceAsync(typeof(SVsActivityLog))
                                         .ConfigureAwait(true).GetAwaiter().GetResult() as IVsActivityLog;
            //if (activityLog == null) return;
            //System.Windows.Forms.MessageBox.Show("Found the activity log service.");
            ThreadHelper.ThrowIfNotOnUIThread();
            DTE dte = (DTE)package.GetServiceAsync(typeof(DTE)).ConfigureAwait(true).GetAwaiter().GetResult();
            events      = dte.Events;
            docEvents   = dte.Events.DocumentEvents;
            buildEvents = dte.Events.BuildEvents;

            RegisterToDTEEvents();

            Owner.LocationChanged += Owner_LocationChanged;
            Owner.StateChanged    += Owner_StateOrSizeChanged;
            Owner.SizeChanged     += Owner_StateOrSizeChanged;

            LocationChanged += SpriteContainer_LocationChanged;

            #endregion

            #region -- Restore Sprite postion --

            double?storedRelativeTop  = null;
            double?storedRelativeLeft = null;

            double relativeTop  = 0;
            double relativeLeft = 0;

            try
            {
                if (_userSettingsStore.PropertyExists(Constants.SettingsCollectionPath, nameof(RelativeTop)))
                {
                    storedRelativeTop = double.Parse(_userSettingsStore.GetString(Constants.SettingsCollectionPath, nameof(RelativeTop)), CultureInfo.InvariantCulture);
                }

                if (_userSettingsStore.PropertyExists(Constants.SettingsCollectionPath, nameof(RelativeLeft)))
                {
                    storedRelativeLeft = Double.Parse(_userSettingsStore.GetString(Constants.SettingsCollectionPath, nameof(RelativeLeft)), CultureInfo.InvariantCulture);
                }
            }
            catch (Exception e)
            {
                Debug.Fail(e.Message);
            }

            if (!storedRelativeTop.HasValue || !storedRelativeLeft.HasValue)
            {
                recalculateSpritePosition(out relativeTop, out relativeLeft, true);
                storedRelativeTop  = relativeTop;
                storedRelativeLeft = relativeLeft;

                this.RelativeLeft = relativeLeft;
                this.RelativeTop  = relativeTop;

                storeRelativeSpritePosition(storedRelativeTop.Value, storedRelativeLeft.Value);
            }
            else
            {
                recalculateSpritePosition(out relativeTop, out relativeLeft);

                this.RelativeLeft = relativeLeft;
                this.RelativeTop  = relativeTop;
            }

            double ownerTop  = this.Owner.Top;
            double ownerLeft = this.Owner.Left;

            if (this.Owner.WindowState == WindowState.Maximized)
            {
                ownerTop  = 0;
                ownerLeft = 0;
            }

            this.Top  = ownerTop + storedRelativeTop.Value;
            this.Left = ownerLeft + storedRelativeLeft.Value;

            #endregion

            var values = Enum.GetValues(typeof(ClippyAnimation));

            //// TEMP: create a voice for each animation in the context menu
            //var pMenu = (ContextMenu)this.Resources["cmButton"];

            //foreach (ClippySingleAnimation val in values)
            //{
            //    var menuItem = new MenuItem()
            //    {
            //        Header = val.ToString(),
            //        Name = "cmd" + val.ToString()
            //    };
            //    menuItem.Click += cmdTestAnimation_Click;
            //    pMenu.Items.Add(menuItem);
            //}
            //// /TEMP

            _clippy = new Clippy((Canvas)FindName("ClippyCanvas"));
            _clippy.StartAnimation(ClippyAnimation.Idle1_1);
        }
Example #19
0
 /// <summary>
 /// Initializes a new <see cref="ActivityLogger"/>.
 /// </summary>
 /// <param name="activityLog">The Visual Studio activity log</param>
 /// <param name="logType">The type a logger is for</param>
 public ActivityLogger(IVsActivityLog activityLog, Type logType)
 {
     _activityLog = activityLog;
     _logType     = logType;
 }
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            try
            {
                Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this));

                base.Initialize();

                // InitializePackageServices
                _dte = (DTE2)GetGlobalService(typeof(DTE));

                _log = GetService(typeof(SVsActivityLog)) as IVsActivityLog;

                // Initialize Tools->Options Page
                _options = (OptionsPageGeneral)GetDialogPage(typeof(OptionsPageGeneral));

                // Initialize Solution Service Events
                _solutionService = (IVsSolution2)GetGlobalService(typeof(SVsSolution));
                if (_solutionService != null)
                {
                    _solutionService.AdviseSolutionEvents(this, out _solutionEventsCookie);
                }
				
                _debuggerEvents = (EnvDTE.DebuggerEvents)_dte.Events.DebuggerEvents;
                _debuggerEvents.OnEnterRunMode += new _dispDebuggerEvents_OnEnterRunModeEventHandler(OnEnterRunMode); ;
                _debuggerEvents.OnEnterDesignMode += new _dispDebuggerEvents_OnEnterDesignModeEventHandler(OnEnterDesignMode); ;

                //InitializeOutputWindowPane
                if (_dte != null
                    && _dte.ToolWindows.OutputWindow.OutputWindowPanes.Cast<OutputWindowPane>().All(p => p.Name != _options.OutputPane))
                {
                    _dte.ToolWindows.OutputWindow.OutputWindowPanes.Add(_options.OutputPane);
                }

                InitializeMenus();
                InitializeAutoShelve();
            }
            catch (Exception ex)
            {
                WriteException(ex);
            }
        }
Example #21
0
        private static void LogException(
            IVsActivityLog log,
            string message,
            string path,
            Exception ex,
            IEnumerable<object> data = null
        ) {
            if (log == null) {
                return;
            }

            var fullMessage = string.Format("{1}:{0}{2}{0}{3}",
                Environment.NewLine,
                message,
                ex,
                data == null ? string.Empty : string.Join(Environment.NewLine, data)
            ).Trim();

            if (string.IsNullOrEmpty(path)) {
                log.LogEntry(
                    (uint)__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR,
                    "Python Tools",
                    fullMessage
                );
            } else {
                log.LogEntryPath(
                    (uint)__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR,
                    "Python Tools",
                    fullMessage,
                    path
                );
            }
        }
Example #22
0
        public async Task QuickRefreshNodesGlyphs(IVsSccProject2 project, List <string> files)
        {
            try
            {
                if (files.Count > 0)
                {
                    string[] rgpszFullPaths = new string[files.Count];
                    for (int i = 0; i < files.Count; i++)
                    {
                        rgpszFullPaths[i] = files[i];
                    }

                    VsStateIcon[] rgsiGlyphs    = new VsStateIcon[files.Count];
                    uint[]        rgdwSccStatus = new uint[files.Count];
                    GetSccGlyph(files.Count, rgpszFullPaths, rgsiGlyphs, rgdwSccStatus);

                    uint[] rguiAffectedNodes = new uint[files.Count];

                    //TODO We could/Should cache this mapping !!!!
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    IList <uint> subnodes = await SolutionExtensions.GetProjectItems((IVsHierarchy)project, VSConstants.VSITEMID_ROOT);

                    var dict = new Dictionary <string, uint>();
                    var proj = project as IVsProject2;

                    foreach (var id in subnodes)
                    {
                        string docname;
                        var    res = proj.GetMkDocument(id, out docname);

                        if (res == VSConstants.S_OK && !string.IsNullOrEmpty(docname))
                        {
                            dict[docname] = id;
                        }
                    }

                    for (int i = 0; i < files.Count; ++i)
                    {
                        uint id;
                        if (dict.TryGetValue(files[i], out id))
                        {
                            rguiAffectedNodes[i] = id;
                        }
                    }
                    await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    project.SccGlyphChanged(files.Count, rguiAffectedNodes, rgsiGlyphs, rgdwSccStatus);
                }
            }
            catch (Exception ex)
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                IVsActivityLog log = _sccProvider.GetService(typeof(SVsActivityLog)) as IVsActivityLog;
                if (log == null)
                {
                    return;
                }

                int hr = log.LogEntry((UInt32)__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR,
                                      ex.StackTrace,
                                      string.Format(CultureInfo.CurrentCulture,
                                                    "Called for: {0}", this.ToString()));
            }
        }
Example #23
0
        private static void LoadOneProvider(
            string codebase,
            HashSet<string> seen,
            List<ComposablePartCatalog> catalog,
            IVsActivityLog log
        ) {
            if (string.IsNullOrEmpty(codebase)) {
                return;
            }
            
            if (!seen.Add(codebase)) {
                return;
            }

            if (log != null) {
                log.LogEntryPath(
                    (uint)__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION,
                    "Python Tools",
                    "Loading interpreter provider assembly",
                    codebase
                );
            }

            AssemblyCatalog assemblyCatalog = null;

            const string FailedToLoadAssemblyMessage = "Failed to load interpreter provider assembly";
            try {
                assemblyCatalog = new AssemblyCatalog(codebase);
            } catch (Exception ex) {
                LogException(log, FailedToLoadAssemblyMessage, codebase, ex);
            }

            if (assemblyCatalog == null) {
                return;
            }

            const string FailedToLoadMessage = "Failed to load interpreter provider";
            try {
                catalog.Add(assemblyCatalog);
            } catch (Exception ex) {
                LogException(log, FailedToLoadMessage, codebase, ex);
            }
        }
 public VisualStudioActivityLogger(IVsActivityLog vsActivityLog)
 {
     _vsActivityLog = vsActivityLog;
 }
Example #25
0
        public InterpreterOptionsService([Import(typeof(SVsServiceProvider), AllowDefault = true)] IServiceProvider provider) {
            _serviceThread = Thread.CurrentThread;
#if !DEV12_OR_LATER
            _serviceContext = SynchronizationContext.Current;
#endif
            _settings = SettingsManagerCreator.GetSettingsManager(provider);
            if (provider != null) {
                _activityLog = provider.GetService(typeof(SVsActivityLog)) as IVsActivityLog;
            } else if (ServiceProvider.GlobalProvider != null) {
                _activityLog = ServiceProvider.GlobalProvider.GetService(typeof(SVsActivityLog)) as IVsActivityLog;
            }
            Initialize(provider);

            InitializeDefaultInterpreterWatcher(provider);
        }
Example #26
0
 private void InitializeActivityLog()
 {
     this.activityLog = (IVsActivityLog)GetService(typeof(SVsActivityLog));
 }
Example #27
0
 public PrigActivityLog(IVsActivityLog activityLog)
     : base("Prig", activityLog)
 {
 }
 public static void LogInformation(this IVsActivityLog logger, string packageName, string message)
 {
     logger.LogEntry((UInt32)__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION, packageName, message);
 }
        /// <summary>
        /// The event explorer user control constructor.
        /// </summary>
        public RdtEventControl()
        {
            InitializeComponent();

            // Create a selection container for tracking selected RDT events.
            selectionContainer = new MsVsShell.SelectionContainer();

            // Advise the RDT of this event sink.
            IOleServiceProvider sp =
                Package.GetGlobalService(typeof(IOleServiceProvider)) as IOleServiceProvider;

            if (sp == null)
            {
                return;
            }

            rdt = new RunningDocumentTable(new ServiceProvider(sp));
            if (rdt == null)
            {
                return;
            }

            rdtCookie = rdt.Advise(this);

            // Obtain the single instance of the options via automation.
            try
            {
                DTE dte = (DTE)Package.GetGlobalService(typeof(DTE));

                Properties props =
                    dte.get_Properties("RDT Event Explorer", "Explorer Options");

                IOptions o = props.Item("ContainedOptions").Object as IOptions;
                options = (Options)o;
            }
            catch
            {
                IVsActivityLog log = Package.GetGlobalService(
                    typeof(SVsActivityLog)) as IVsActivityLog;
                if (log != null)
                {
                    log.LogEntry(
                        (uint)__ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION,
                        ToString(),
                        string.Format(CultureInfo.CurrentCulture,
                                      "RdtEventExplorer could not obtain properties via automation: {0}",
                                      ToString())
                        );
                }
                options = new Options();
            }
            // Prepare the event grid.
            eventGrid.AutoGenerateColumns = false;
            eventGrid.AllowUserToAddRows  = false;
            eventGrid.SelectionMode       = DataGridViewSelectionMode.FullRowSelect;

            eventGrid.Columns.Add("Event", Resources.EventHeader);
            eventGrid.Columns.Add("Moniker", Resources.MonikerHeader);
            eventGrid.Columns["Event"].ReadOnly   = true;
            eventGrid.Columns["Moniker"].ReadOnly = true;

            eventGrid.AllowUserToResizeRows    = false;
            eventGrid.AllowUserToResizeColumns = true;
            eventGrid.AutoSizeColumnsMode      = DataGridViewAutoSizeColumnsMode.Fill;

            int x = Screen.PrimaryScreen.Bounds.Size.Width;
            int y = Screen.PrimaryScreen.Bounds.Size.Height;

            Size = new Size(x / 3, y / 3);
        }
 public LogService(IVsActivityLog activityLog)
 {
     _activityLog = activityLog;
 }
Example #31
0
        private void UpdateIncludesOnBeforeSave(VCProject p, string projectDirectory)
        {
            var(includesSaved, macrosSaved) = ProjectIncludesManager.CheckSavedIncludesAndMacros(p);
            IEnumerable <string> includesBefore            = null;
            IEnumerable <CompilerMacroResult> macrosBefore = null;

            try
            {
                ThreadHelper.JoinableTaskFactory.Run("Updating includes and macros", async(progress) =>
                {
                    await Task.Run(() => GetIncludesAndMacros());

                    void GetIncludesAndMacros()
                    {
                        if (!includesSaved)
                        {
                            progress.Report(new ThreadedWaitDialogProgressData("Fetching project information"));
                            ProjectInformationCommandResult projectInformationBefore = null;
                            try
                            {
                                projectInformationBefore = cliCommunication.ExecuteCommand(Resources.Command_get_project_information, null,
                                                                                           typeof(ProjectInformationCommandResult), Resources.Option_get_project_information_project,
                                                                                           $"\"{projectDirectory}\"") as ProjectInformationCommandResult;
                            }
                            catch (PlcncliException ex)
                            {
                                projectInformationBefore = cliCommunication.ConvertToTypedCommandResult <ProjectInformationCommandResult>(ex.InfoMessages);
                            }
                            includesBefore = projectInformationBefore?.IncludePaths.Select(x => x.PathValue);
                            if (includesBefore == null)
                            {
                                includesBefore = Enumerable.Empty <string>();
                            }
                        }

                        if (!macrosSaved)
                        {
                            progress.Report(new ThreadedWaitDialogProgressData("Fetching compiler information"));

                            CompilerSpecificationCommandResult compilerSpecsBefore = null;
                            try
                            {
                                compilerSpecsBefore = cliCommunication.ExecuteCommand(Resources.Command_get_compiler_specifications, null,
                                                                                      typeof(CompilerSpecificationCommandResult), Resources.Option_get_compiler_specifications_project,
                                                                                      $"\"{projectDirectory}\"") as CompilerSpecificationCommandResult;
                            }
                            catch (PlcncliException ex)
                            {
                                compilerSpecsBefore = cliCommunication.ConvertToTypedCommandResult <CompilerSpecificationCommandResult>(ex.InfoMessages);
                            }
                            macrosBefore = compilerSpecsBefore?.Specifications.FirstOrDefault()
                                           ?.CompilerMacros.Where(m => !m.Name.StartsWith("__has_include(")) ?? Enumerable.Empty <CompilerMacroResult>();
                        }
                    }
                });

                this.vcProject        = p;
                this.projectDirectory = p.ProjectDirectory;
                this.wrapper          = new IncludesAndMacrosWrapper(includesBefore, macrosBefore);
            }
            catch (Exception e)
            {
                Reset();
                try
                {
                    ThreadHelper.ThrowIfNotOnUIThread();
                    IVsActivityLog log = Package.GetGlobalService(typeof(SVsActivityLog)) as IVsActivityLog;
                    log.LogEntry((uint)__ACTIVITYLOG_ENTRYTYPE.ALE_ERROR, this.ToString(),
                                 "An error occurred while updating the includes: " + e.Message + e.StackTrace);
                }
                catch (Exception) { /*try to log error in activity log*/ }
            }
        }
Example #32
0
        /// <summary>
        /// Set up Visual Studio activity logger.
        /// </summary>
        private void SetUpActivityLogger() {
            SrcMLFileLogger.DefaultLogger.Info("> Set up Visual Studio activity logger.");

            ActivityLog = GetService(typeof(SVsActivityLog)) as IVsActivityLog;
            if(null == ActivityLog) {
                Trace.WriteLine("Can not get the Activity Log service.");
            }
        }
Example #33
0
 public VsLogger(ServiceAccessor serviceAccessor, JoinableTaskFactory joinableTaskFactory)
 {
     _logger = serviceAccessor.GetService(typeof(SVsActivityLog)) as IVsActivityLog;
     _joinableTaskFactory = joinableTaskFactory;
 }
Example #34
0
 public LogService(IVsActivityLog activityLog)
 {
     _activityLog = activityLog;
 }
Example #35
0
 public void Initialize(IVsActivityLog log)
 {
     _log = log;
 }