Ejemplo n.º 1
0
 public WaitDialog(string waitCaption, string waitMessage, IServiceProvider serviceProvider, int displayDelay = 1, bool isCancelable = false, bool showProgress = false) {
     _waitDialog = (IVsThreadedWaitDialog2)serviceProvider.GetService(typeof(SVsThreadedWaitDialog));
     _waitResult = _waitDialog.StartWaitDialog(
         waitCaption,
         waitMessage,
         null,
         null,
         null,
         displayDelay,
         isCancelable,
         showProgress
     );
 }
Ejemplo n.º 2
0
 public WaitDialog(string waitCaption, string waitMessage, IServiceProvider serviceProvider, int displayDelay = 1, bool isCancelable = false, bool showProgress = false)
 {
     this._waitDialog = (IVsThreadedWaitDialog2)serviceProvider.GetService(typeof(SVsThreadedWaitDialog));
     this._waitResult = this._waitDialog.StartWaitDialog(
         waitCaption,
         waitMessage,
         null,
         null,
         null,
         displayDelay,
         isCancelable,
         showProgress
         );
 }
        private void UpdateSlowCheetah(Project project)
        {
            // This is done on the UI thread because changes are made to the project file,
            // causing it to be reloaded. To avoid conflicts with NuGet installation,
            // the update is done sequentially
            if (this.HasUserAcceptedWarningMessage(Resources.Resources.NugetUpdate_Title, Resources.Resources.NugetUpdate_Text))
            {
                // Creates dialog informing the user to wait for the installation to finish
                IVsThreadedWaitDialogFactory twdFactory = this.package.GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;
                IVsThreadedWaitDialog2       dialog     = null;
                twdFactory?.CreateInstance(out dialog);

                string title = Resources.Resources.NugetUpdate_WaitTitle;
                string text  = Resources.Resources.NugetUpdate_WaitText;
                dialog?.StartWaitDialog(title, text, null, null, null, 0, false, true);
                try
                {
                    // Installs the latest version of the SlowCheetah NuGet package
                    var componentModel = (IComponentModel)this.package.GetService(typeof(SComponentModel));
                    if (this.IsSlowCheetahInstalled(project))
                    {
                        IVsPackageUninstaller packageUninstaller = componentModel.GetService <IVsPackageUninstaller>();
                        packageUninstaller.UninstallPackage(project, PackageName, true);
                    }

                    IVsPackageInstaller2 packageInstaller = componentModel.GetService <IVsPackageInstaller2>();
                    packageInstaller.InstallLatestPackage(null, project, PackageName, false, false);

                    project.Save();
                    ProjectRootElement projectRoot = ProjectRootElement.Open(project.FullName);
                    foreach (ProjectPropertyGroupElement propertyGroup in projectRoot.PropertyGroups.Where(pg => pg.Label.Equals("SlowCheetah")))
                    {
                        projectRoot.RemoveChild(propertyGroup);
                    }

                    foreach (ProjectImportElement import in projectRoot.Imports.Where(i => i.Label == "SlowCheetah" || i.Project == "$(SlowCheetahTargets)"))
                    {
                        projectRoot.RemoveChild(import);
                    }

                    projectRoot.Save();
                }
                finally
                {
                    // Closes the wait dialog. If the dialog failed, does nothing
                    dialog?.EndWaitDialog(out int canceled);
                }
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Creates the threaded wait dialog, see <b>Microsoft.VisualStudio.Shell.Interop.IVsThreadedWaitDialog2</b>
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="progress">The progress.</param>
        /// <param name="statustext">The statustext.</param>
        /// <param name="total">The total.</param>
        /// <returns>"Microsoft.VisualStudio.Shell.Interop.IVsThreadedWaitDialog2" instance</returns>
        static internal IVsThreadedWaitDialog2 CreateThreadedWaitDialog(string message, string progress, string statustext, int total)
        {
            //dlg = Utilities.CreateThreadedWaitDialog("Collecting information about changesets", "Starting to process changests...", "status", 100);
            //dlg.UpdateProgress("Collecting information about changesets", "Starting to process changesets...", "status", 0, 100, true, out bcanceled);
            //dlg.EndWaitDialog(out icanceled);

            IVsThreadedWaitDialog2 dlg = null;

            ErrorHandler.ThrowOnFailure(dialogFactory.CreateInstance(out dlg));

            ErrorHandler.ThrowOnFailure(
                dlg.StartWaitDialogWithPercentageProgress(AppTitle, message, progress, null, statustext, true, 0, total, 0));

            return(dlg);
        }
Ejemplo n.º 5
0
            public ThreadedWaitWrapper(IVsThreadedWaitDialogFactory factory, string caption, string message)
            {
                if (factory == null)
                {
                    return;
                }

                if (!VSErr.Succeeded(factory.CreateInstance(out _dlg2)))
                {
                    _dlg2 = null;
                    return;
                }

                _dlg2.StartWaitDialog(caption, message, null, null, null, 2, false, true);
            }
Ejemplo n.º 6
0
        private void OnTrialAndErrorRemovalDone(IVsThreadedWaitDialog2 progressDialog, EnvDTE.Document document, int numRemovedIncludes, bool canceled)
        {
            // Close Progress bar.
            progressDialog.EndWaitDialog();

            // Remove build hook again.
            UnsubscribeBuildEvents();

            // Message.
            Output.Instance.WriteLine("Removed {0} #include directives from '{1}'", numRemovedIncludes, document.Name);
            Output.Instance.OutputToForeground();

            // Notify that we are done.
            WorkInProgress = false;
            OnFileFinished?.Invoke(numRemovedIncludes, canceled);
        }
        public static IVsThreadedWaitDialog2 ShowWaitDialog(IVsThreadedWaitDialogFactory dialogFactory)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            IVsThreadedWaitDialog2 dialog = null;

            if (dialogFactory != null)
            {
                dialogFactory.CreateInstance(out dialog);
            }


            if (dialog != null)
            {
                dialog.StartWaitDialog(Messages.PleaseWait, Messages.ExecutingRequestedAction, "", null, "", 0, false, true);
            }
            return(dialog);
        }
        private void StartProgressBar(string title, string message, string progressMessage)
        {
            var dialogFactory             = GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;
            IVsThreadedWaitDialog2 dialog = null;

            if (dialogFactory != null)
            {
                dialogFactory.CreateInstance(out dialog);
            }

            attachingDialog = (IVsThreadedWaitDialog3)dialog;

            attachingDialog.StartWaitDialogWithCallback(title,
                                                        message, string.Empty, null,
                                                        progressMessage, true, 0,
                                                        true, 0, 0, this);
        }
Ejemplo n.º 9
0
        public VSWaitDialog(string format, string caption)
        {
            _format = format;
            _caption = caption;
            var waitDialogFactory = (IVsThreadedWaitDialogFactory)Package.GetGlobalService(typeof(SVsThreadedWaitDialogFactory));
            if (waitDialogFactory == null)
            {
                return; // normal case in glass
            }

            IVsThreadedWaitDialog2 waitDialog;
            int hr = waitDialogFactory.CreateInstance(out waitDialog);
            if (hr != VSConstants.S_OK) return;

            _waitDialog = waitDialog;
            _started = false;
        }
Ejemplo n.º 10
0
        private IVsThreadedWaitDialog2 ShowProgressDialog(string caption, string message)
        {
            IOleServiceProvider          oleServiceProvider = dteObject as IOleServiceProvider;
            IVsThreadedWaitDialogFactory dialogFactory      = new ServiceProvider(oleServiceProvider).GetService(
                typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;

            if (dialogFactory == null)
            {
                throw new InvalidOperationException("The IVsThreadedWaitDialogFactory object could not be retrieved.");
            }

            IVsThreadedWaitDialog2 vsThreadedWaitDialog = null;

            ErrorHandler.ThrowOnFailure(dialogFactory.CreateInstance(out vsThreadedWaitDialog));
            ErrorHandler.ThrowOnFailure(vsThreadedWaitDialog.StartWaitDialog(caption, message,
                                                                             null, null, String.Empty, 0, false, true));
            return(vsThreadedWaitDialog);
        }
Ejemplo n.º 11
0
        private async Task OptionalDownloadOrUpdate(IncludeWhatYouUseOptionsPage settings, IVsThreadedWaitDialogFactory dialogFactory)
        {
            // Check existence, offer to download if it's not there.
            bool downloadedNewIwyu = false;

            if (!File.Exists(settings.ExecutablePath))
            {
                if (await Output.Instance.YesNoMsg($"Can't find include-what-you-use in '{settings.ExecutablePath}'. Do you want to download it from '{IWYUDownload.DisplayRepositorURL}'?") != Output.MessageResult.Yes)
                {
                    return;
                }

                downloadedNewIwyu = await DownloadIWYUWithProgressBar(settings.ExecutablePath, dialogFactory);

                if (!downloadedNewIwyu)
                {
                    return;
                }
            }
            else if (settings.AutomaticCheckForUpdates && !checkedForUpdatesThisSession)
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                IVsThreadedWaitDialog2 dialog = null;
                dialogFactory.CreateInstance(out dialog);
                dialog?.StartWaitDialog("Include Toolbox", "Running Include-What-You-Use", null, null, "Checking for Updates for include-what-you-use", 0, false, true);
                bool newVersionAvailable = await IWYUDownload.IsNewerVersionAvailableOnline(settings.ExecutablePath);

                dialog?.EndWaitDialog();

                if (newVersionAvailable)
                {
                    checkedForUpdatesThisSession = true;
                    if (await Output.Instance.YesNoMsg($"There is a new version of include-what-you-use available. Do you want to download it from '{IWYUDownload.DisplayRepositorURL}'?") == Output.MessageResult.Yes)
                    {
                        downloadedNewIwyu = await DownloadIWYUWithProgressBar(settings.ExecutablePath, dialogFactory);
                    }
                }
            }
            if (downloadedNewIwyu)
            {
                settings.AddMappingFiles(IWYUDownload.GetMappingFilesNextToIwyuPath(settings.ExecutablePath));
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AddMediatRItemCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        /// <param name="commandService">Command service to add command to, not null.</param>
        private AddMediatRItemCommand(AsyncPackage package, OleMenuCommandService commandService)
        {
            this.package   = package ?? throw new ArgumentNullException(nameof(package));
            commandService = commandService ?? throw new ArgumentNullException(nameof(commandService));

            var settingsManager       = new ShellSettingsManager(this.package);
            var writableSettingsStore = settingsManager.GetWritableSettingsStore(SettingsScope.UserSettings);

            this.mediatrSettingsStoreManager = new MediatRSettingsStoreManager(writableSettingsStore);
            Assumes.Present(this.mediatrSettingsStoreManager);

            this.waitDialog = this.package.GetService <SVsThreadedWaitDialog, IVsThreadedWaitDialog2>();
            Assumes.Present(this.waitDialog);

            var menuCommandID = new CommandID(CommandSet, CommandId);
            var menuItem      = new MenuCommand(this.Execute, menuCommandID);

            commandService.AddCommand(menuItem);
        }
Ejemplo n.º 13
0
        // Specifies whether the current site URL is valid. Uses the ValidateSite SharePoint command to do this.
        internal bool ValidateCurrentUrl(out string errorMessage)
        {
            bool isValid = false;

            errorMessage = String.Empty;

            if (validatedUrls.Contains(CurrentSiteUrl))
            {
                isValid = true;
            }
            else
            {
                Uri uriToValidate = new Uri(CurrentSiteUrl, UriKind.Absolute);
                IVsThreadedWaitDialog2 vsThreadedWaitDialog = null;

                try
                {
                    vsThreadedWaitDialog = ShowProgressDialog("Connect to SharePoint",
                                                              "Connecting to SharePoint site " + CurrentSiteUrl);
                    isValid = this.ProjectService.SharePointConnection.ExecuteCommand <Uri, bool>(
                        Contoso.SharePoint.Commands.CommandIds.ValidateSite, uriToValidate);
                }
                catch (Exception ex)
                {
                    errorMessage = "An error occurred while validating the site. " + ex.Message;
                }
                finally
                {
                    if (isValid)
                    {
                        validatedUrls.Add(CurrentSiteUrl);
                    }

                    if (vsThreadedWaitDialog != null)
                    {
                        CloseProgressDialog(vsThreadedWaitDialog);
                    }
                }
            }

            return(isValid);
        }
Ejemplo n.º 14
0
        private async Task StartProgressBarAsync(string title, string message, string progressMessage)
        {
            await package.JoinableTaskFactory.SwitchToMainThreadAsync();

            var dialogFactory = await this.ServiceProvider.GetServiceAsync(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;

            IVsThreadedWaitDialog2 dialog = null;

            if (dialogFactory != null)
            {
                dialogFactory.CreateInstance(out dialog);
            }

            attachingDialog = (IVsThreadedWaitDialog3)dialog;

            attachingDialog.StartWaitDialogWithCallback(title,
                                                        message, string.Empty, null,
                                                        progressMessage, true, 0,
                                                        true, 0, 0, this);
        }
Ejemplo n.º 15
0
        void CreateProgressDialog()
        {
            var dialogFactory = GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;
            IVsThreadedWaitDialog2 progressDialog = null;

            if (dialogFactory != null)
            {
                dialogFactory.CreateInstance(out progressDialog);
            }

            if (progressDialog != null &&
                progressDialog.StartWaitDialog(
                    ResolveUR.Library.Constants.AppName + " Working...",
                    "Visual Studio is busy. Cancel ResolveUR by clicking Cancel button",
                    string.Empty,
                    null,
                    string.Empty,
                    0,
                    true,
                    true) == VSConstants.S_OK)
            {
                Thread.Sleep(1000);
            }

            _helper.ProgressDialog = progressDialog;

            var dialogCanceled = false;

            if (progressDialog != null)
            {
                progressDialog.HasCanceled(out dialogCanceled);
            }

            if (!dialogCanceled)
            {
                return;
            }

            _resolveur.Cancel();
            _helper.ShowMessageBox(ResolveUR.Library.Constants.AppName + " Status", "Canceled");
        }
        /// <summary>
        ///     This function is the callback used to execute the command when the menu item is clicked. See the
        ///     constructor to see how the menu item is associated with this function using OleMenuCommandService
        ///     service and MenuCommand class.
        /// </summary>
        /// <param name="sender"> Event sender. </param>
        /// <param name="e"> Event args. </param>
        private void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var dte = _sdteService as DTE;

            if (dte.SelectedItems.Count <= 0)
            {
                return;
            }

            var totalCount = _selectedItemCountExecutor.Execute(dte.SelectedItems);

            IVsThreadedWaitDialog2 dialog = null;

            if (totalCount > 1 && _dialogFactory != null)
            {
                //https://www.visualstudiogeeks.com/extensions/visualstudio/using-progress-dialog-in-visual-studio-extensions
                _dialogFactory.CreateInstance(out dialog);
            }

            var cts = new CancellationTokenSource();

            if (dialog == null ||
                dialog.StartWaitDialogWithPercentageProgress("Proto Attributor: Attributing Progress", "", $"0 of {totalCount} Processed",
                                                             null, DIALOG_ACTION, true, 0, totalCount, 0) != VSConstants.S_OK)
            {
                dialog = null;
            }

            try
            {
                _attributeExecutor.Execute(dte.SelectedItems, cts, dialog, totalCount, _textSelectionExecutor,
                                           (content) => _attributeService.ReorderAttributes(content));
            }
            finally
            {
                dialog?.EndWaitDialog(out var usercancel);
            }
        }
Ejemplo n.º 17
0
        public VSWaitDialog(string format, string caption)
        {
            _format  = format;
            _caption = caption;
            var waitDialogFactory = (IVsThreadedWaitDialogFactory)Package.GetGlobalService(typeof(SVsThreadedWaitDialogFactory));

            if (waitDialogFactory == null)
            {
                return; // normal case in glass
            }

            IVsThreadedWaitDialog2 waitDialog;
            int hr = waitDialogFactory.CreateInstance(out waitDialog);

            if (hr != VSConstants.S_OK)
            {
                return;
            }

            _waitDialog = waitDialog;
            _started    = false;
        }
        private void ThreadedNonCancellable_Click(object sender, RoutedEventArgs e)
        {
            var dialogFactory             = _serviceProvider.GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;
            IVsThreadedWaitDialog2 dialog = null;

            if (dialogFactory != null)
            {
                dialogFactory.CreateInstance(out dialog);
            }

            /* Wait dialog with marquee progress */
            if (dialog != null && dialog.StartWaitDialog(
                    "Threaded Wait Dialog", "VS is Busy",
                    "Progress text", null,
                    "Waiting status bar text",
                    0, false,
                    true) == VSConstants.S_OK)
            {
                Thread.Sleep(4000);
            }
            int usercancel;

            dialog.EndWaitDialog(out usercancel);
        }
Ejemplo n.º 19
0
        /// <inheritdoc/>
        public override void Execute(Project project)
        {
            if (this.HasUserAcceptedWarningMessage(Resources.Resources.NugetUpdate_Title, Resources.Resources.NugetUpdate_Text))
            {
                // Creates dialog informing the user to wait for the installation to finish
                IVsThreadedWaitDialogFactory twdFactory = this.Package.GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;
                IVsThreadedWaitDialog2       dialog     = null;
                twdFactory?.CreateInstance(out dialog);

                string title = Resources.Resources.NugetUpdate_WaitTitle;
                string text  = Resources.Resources.NugetUpdate_WaitText;
                dialog?.StartWaitDialog(title, text, null, null, null, 0, false, true);

                try
                {
                    this.Successor.Execute(project);
                }
                finally
                {
                    // Closes the wait dialog. If the dialog failed, does nothing
                    dialog?.EndWaitDialog(out int canceled);
                }
            }
        }
Ejemplo n.º 20
0
        public override void NextBtnCommandAction(Object param)
        {
            switch (CurrentUiStepId)
            {
            case 0:
                CurrentUiStepId = 1;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                SaveBtnEnabled  = false;
                if (SelectDbContextUC == null)
                {
                    SelectDbContextViewModel dataContext = new SelectDbContextViewModel(Dte);
                    dataContext.UiCommandButtonVisibility = Visibility.Collapsed;
                    dataContext.UiCommandCaption3         = "NameSpace: " + (InvitationUC.DataContext as InvitationViewModel).DefaultProjectNameSpace;
                    string folder = (InvitationUC.DataContext as InvitationViewModel).DestinationFolder;
                    if (!string.IsNullOrEmpty(folder))
                    {
                        dataContext.UiCommandCaption3 = dataContext.UiCommandCaption3 + "." + folder.Replace("\\", ".");
                    }
                    SelectDbContextUC = new UserControlSelectSource(dataContext);
                    dataContext.IsReady.IsReadyEvent += CallBack_IsReady;
                }
                (SelectDbContextUC.DataContext as SelectDbContextViewModel).DoAnaliseDbContext();
                this.CurrentUserControl = SelectDbContextUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            case 1:
                CurrentUiStepId = 2;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                if (CreateWebApiUC == null)
                {
                    CreateWebApiViewModel dataContext = new CreateWebApiViewModel(Dte);
                    dataContext.IsReady.IsReadyEvent   += CallBack_IsReady;
                    dataContext.DestinationProject      = (InvitationUC.DataContext as InvitationViewModel).DestinationProject;
                    dataContext.DefaultProjectNameSpace = (InvitationUC.DataContext as InvitationViewModel).DefaultProjectNameSpace;
                    dataContext.DestinationFolder       = (InvitationUC.DataContext as InvitationViewModel).DestinationFolder;
                    CreateWebApiUC = new UserControlCreateWebApi(dataContext);
                }
                (CreateWebApiUC.DataContext as CreateWebApiViewModel).SelectedDbContext =
                    (SelectDbContextUC.DataContext as SelectDbContextViewModel).SelectedCodeElement;
                (CreateWebApiUC.DataContext as CreateWebApiViewModel).CheckIsReady();
                this.CurrentUserControl = CreateWebApiUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            case 2:
                CurrentUiStepId = 3;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                if (T4EditorUC == null)
                {
                    //string templatePath = Path.Combine("Templates", "ViewModel.cs.t4");
                    string            TemplatesFld = TemplatePathHelper.GetTemplatePath();
                    string            templatePath = Path.Combine(TemplatesFld, "WebApiServiceTmplst");
                    T4EditorViewModel dataContext  = new T4EditorViewModel(templatePath);
                    dataContext.IsReady.IsReadyEvent += CallBack_IsReady;
                    T4EditorUC = new UserControlT4Editor(dataContext);
                }
                (T4EditorUC.DataContext as T4EditorViewModel).CheckIsReady();
                this.CurrentUserControl = T4EditorUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            case 3:
                CurrentUiStepId = 4;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = true;
                IVsThreadedWaitDialog2 aDialog = null;
                bool aDialogStarted            = false;
                if (this.DialogFactory != null)
                {
                    this.DialogFactory.CreateInstance(out aDialog);
                    if (aDialog != null)
                    {
                        aDialogStarted = aDialog.StartWaitDialog("Generation started", "VS is Busy", "Please wait", null, "Generation started", 0, false, true) == VSConstants.S_OK;
                    }
                }
                if (GenerateUC == null)
                {
                    GenerateCommonStaffViewModel dataContext = new GenerateCommonStaffViewModel();
                    dataContext.IsReady.IsReadyEvent += GenerateWebApiViewModel_IsReady;
                    GenerateUC = new UserControlGenerate(dataContext);
                }

                (GenerateUC.DataContext as GenerateCommonStaffViewModel).GenText = (T4EditorUC.DataContext as T4EditorViewModel).T4TempateText;

                try
                {
                    (GenerateUC.DataContext as GenerateCommonStaffViewModel)
                    .DoGenerateViewModel(Dte, TextTemplating,
                                         (T4EditorUC.DataContext as T4EditorViewModel).T4TempatePath,
                                         (CreateWebApiUC.DataContext as CreateWebApiViewModel).SerializableDbContext,
                                         (CreateWebApiUC.DataContext as CreateWebApiViewModel).GetSelectedModelShallowCopy());
                    if (aDialogStarted)
                    {
                        int iOut;
                        aDialog.EndWaitDialog(out iOut);
                    }
                }
                catch (Exception e)
                {
                    if (aDialogStarted)
                    {
                        int iOut;
                        aDialog.EndWaitDialog(out iOut);
                    }
                    MessageBox.Show("Error: " + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    this.CurrentUserControl = GenerateUC;
                    this.OnPropertyChanged("CurrentUserControl");
                }
                break;

            case 4:
                CurrentUiStepId = 2;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                SaveBtnEnabled  = false;
                (CreateWebApiUC.DataContext as CreateWebApiViewModel).CheckIsReady();
                this.CurrentUserControl = CreateWebApiUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            default:
                break;
            }
        }
Ejemplo n.º 21
0
        public virtual void StartBtnCommandBatchAction(Object param)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
            IVsThreadedWaitDialog2 aDialog = null;
            bool aDialogStarted            = false;

            if (this.DialogFactory != null)
            {
                this.DialogFactory.CreateInstance(out aDialog);
                if (aDialog != null)
                {
                    aDialogStarted = aDialog.StartWaitDialog("Generation started", "VS is Busy", "Please wait", null, "Generation started", 0, false, true) == VSConstants.S_OK;
                }
            }
            StringBuilder sb = new StringBuilder();

            try
            {
                sb.AppendLine("Json parsing started");
                BatchSettings batchSettings = BatchSettingsHelper.ReadBatchSettingsFromString(CurrentBatchSetting);
                if (batchSettings == null)
                {
                    throw new Exception("Could not Deserialize Object");
                }
                sb.AppendLine("Json parsing finished");
                if (batchSettings.BatchItems == null)
                {
                    throw new Exception("Batch Items is empty");
                }
                sb.AppendLine("Batch Items processing started");

                foreach (BatchItem batchItem  in batchSettings.BatchItems)
                {
                    ModelViewSerializable currentSerializableModel = SerializableModel;
                    if (!string.IsNullOrEmpty(batchItem.ViewModel))
                    {
                        currentSerializableModel = SerializableDbContext.ModelViews.Where(m => m.ViewName == batchItem.ViewModel).FirstOrDefault();
                        if (currentSerializableModel == null)
                        {
                            throw new Exception("Could not find [" + batchItem.ViewModel + "] of the Batch Item = " + batchItem.GeneratorType);
                        }
                    }
                    sb.AppendLine("Processing Batch Item: [DestinationFolder]=[" + batchItem.DestinationFolder + "]");
                    sb.AppendLine("    [GeneratorType]=[" + batchItem.GeneratorType + "]");
                    sb.AppendLine("        [GeneratorSript]=[" + batchItem.GeneratorSript + "]");
                    string tmpltPath = Path.Combine(T4RootFolder, batchItem.GeneratorType, batchItem.GeneratorSript);
                    string FileName  = "";
                    if (currentSerializableModel.ViewName == ContextItemViewName)
                    {
                        FileName =
                            BatchSettingsHelper.TrimPrefix(Path.GetFileNameWithoutExtension(batchItem.GeneratorType));
                    }
                    else
                    {
                        FileName =
                            currentSerializableModel.ViewName + BatchSettingsHelper.TrimPrefix(Path.GetFileNameWithoutExtension(batchItem.GeneratorType));
                    }
                    FileName = BatchSettingsHelper.GetHyphenedName(FileName);
                    sb.AppendLine("    Batch Item: Creating Shallow Copy");
                    ModelViewSerializable ShallowCopy = null;
                    if (currentSerializableModel.ViewName == SerializableModel.ViewName)
                    {
                        ShallowCopy =
                            BatchSettingsHelper.GetSelectedModelCommonShallowCopy(currentSerializableModel,
                                                                                  UIFormProperties, UIListProperties,
                                                                                  DestinationProjectName, DefaultProjectNameSpace, DestinationFolder, batchItem.DestinationFolder,
                                                                                  batchItem.GeneratorType, FileName);
                    }
                    else
                    {
                        ShallowCopy =
                            BatchSettingsHelper.GetSelectedModelCommonShallowCopy(currentSerializableModel,
                                                                                  null, null,
                                                                                  DestinationProjectName, DefaultProjectNameSpace, DestinationFolder, batchItem.DestinationFolder,
                                                                                  batchItem.GeneratorType, FileName);
                    }
                    sb.AppendLine("        Batch Item: Generating Code");
                    GeneratorBatchStep generatorBatchStep = BatchSettingsHelper.DoGenerateViewModel(Dte, TextTemplating, tmpltPath, SerializableDbContext, ShallowCopy, DefaultProjectNameSpace);
                    if (!string.IsNullOrEmpty(generatorBatchStep.GenerateError))
                    {
                        throw new Exception(generatorBatchStep.GenerateError);
                    }
                    sb.AppendLine("            Batch Item: Adding Generated file to project and Updating Wizard's Context Repository");
                    BatchSettingsHelper.UpdateDbContext(Dte, DestinationProject, SelectedDbContext, SerializableDbContext, ShallowCopy,
                                                        ContextItemViewName, batchItem.GeneratorType,
                                                        DestinationProjectRootFolder,
                                                        DestinationFolder,
                                                        batchItem.DestinationFolder,
                                                        FileName, generatorBatchStep.FileExtension,
                                                        generatorBatchStep.GenerateText);
                    currentSerializableModel.CommonStaffs = ShallowCopy.CommonStaffs;
                    sb.AppendLine("Batch Item Processing finished");
                }
                sb.AppendLine("Batch Items processing finished");
            }
            catch (Exception e)
            {
                LastError = "Exception thrown: " + e.Message;
                return;
            }
            finally
            {
                if (aDialogStarted)
                {
                    int iOut;
                    aDialog.EndWaitDialog(out iOut);
                }
                ReportText = sb.ToString();
            }
        }
Ejemplo n.º 22
0
		public virtual int CreateInstance(out IVsThreadedWaitDialog2 ppIVsThreadedWaitDialog) {
			ppIVsThreadedWaitDialog = new WaitDialog();
			return 0;
		}
Ejemplo n.º 23
0
        public static bool ExecuteQueryLimitedFields(IVsThreadedWaitDialog2 dlg, QueryDefinition qdef, string ProjectName, out string[][] qdata)
        {
            bool bcanceled;
            int  progress = 1;
            int  locidx   = 1;
            int  maxlevel = 32;

            WorkItemLinkInfo[] links    = null;
            Hashtable          context  = new Hashtable();
            List <Tag>         qresults = new List <Tag>();
            StringBuilder      strb     = new StringBuilder();
            List <string[]>    lqdata   = new List <string[]>();

            context.Add("project", ProjectName); //@me, @today are filled automatically
            var query = new Query(Utilities.wistore, qdef.QueryText, context);

            if (query.IsLinkQuery)
            {
                links = query.RunLinkQuery();

                WorkItemLinkTypeEnd[] linkTypes = null;
                if (query.IsTreeQuery)
                {
                    linkTypes = query.GetLinkTypes();
                }
                else
                {
                    maxlevel = 1;
                }

                int    idx, flag, level = 0, origidx = 1;
                string origprefix = "";
                foreach (var wilnk in links)
                {
                    if (wilnk.SourceId == 0)
                    {
                        qresults.Add(new Tag()
                        {
                            tWorkItemID = wilnk.TargetId, tlevel = 0, tParentID = 0, tPrefix = (locidx++).ToString()
                        });
                    }

                    Utilities.OutputCommandString(string.Format("SourceId={0} TargetId={1} LinkTypeId={2}", wilnk.SourceId, wilnk.TargetId, wilnk.LinkTypeId));
                }

                List <int> chldarr = new List <int>();
                if (qresults.Count > 0)
                {
                    while (level < maxlevel)
                    {
                        level++;
                        flag   = 0;
                        locidx = 1;
                        foreach (var wilnk in links.Where(x => x.SourceId > 0))
                        {
                            string lnkname = query.IsTreeQuery ? linkTypes.First(x => x.Id == wilnk.LinkTypeId).ImmutableName : wilnk.LinkTypeId.ToString();

                            idx = -1;
                            if ((idx = qresults.IndexOf(new Tag()
                            {
                                tWorkItemID = wilnk.SourceId, tlevel = level - 1
                            })) >= 0)
                            {
                                if (origprefix != qresults[idx].tPrefix)
                                {
                                    if (locidx > 2)
                                    {
                                        var qrescopy = qresults.Skip(origidx + 1).Take(locidx - 1);

                                        Utilities.OutputCommandString("level=" + level + ", qrescopy=" + qrescopy.Select(x => x.tPrefix).Aggregate((x, y) => x + "," + y));

                                        var orig   = qrescopy.GetEnumerator();
                                        var prefix = qrescopy.Select(x => x.tPrefix).Reverse().GetEnumerator();
                                        while (orig.MoveNext() && prefix.MoveNext())
                                        {
                                            orig.Current.tPrefix = prefix.Current;
                                        }
                                    }

                                    locidx     = 1;
                                    origprefix = qresults[idx].tPrefix;
                                    origidx    = idx;
                                }
                                qresults.Insert(idx + 1, new Tag()
                                {
                                    tWorkItemID = wilnk.TargetId, tlevel = level, tLinkTypeID = lnkname, tParentID = wilnk.SourceId, tPrefix = origprefix + "." + (locidx++).ToString()
                                });
                                flag = 1;
                                dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Parsing Work Item #" + wilnk.TargetId.ToString(), "status", progress++, 100, false, out bcanceled);
                                if (progress == 100)
                                {
                                    progress = 0;
                                }
                                if (bcanceled)
                                {
                                    flag = 0;
                                    break;
                                }
                            }
                        }
                        if (flag == 0)
                        {
                            break;
                        }
                    }
                }

                foreach (var tag in qresults)
                {
                    strb.Clear();
                    WorkItem wi = Utilities.wistore.GetWorkItem(tag.tWorkItemID);

                    strb.Clear();
                    string stratt;
                    foreach (Attachment att in wi.Attachments)
                    {
                        strb.Append(att.Name + "~" + att.Uri.ToString() + ";");
                    }
                    stratt = strb.ToString();
                    Utilities.OutputCommandString(stratt);

                    lqdata.Add(new[] { stratt,
                                       tag.tlevel.ToString(),
                                       tag.tPrefix,
                                       wi[CoreFieldReferenceNames.WorkItemType].ToString(),
                                       wi[CoreFieldReferenceNames.Id].ToString(),
                                       wi[CoreFieldReferenceNames.Title].ToString(),
                                       wi[CoreFieldReferenceNames.Description].ToString() });

                    dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Adding to collection Work Item #" + wi.Id.ToString(), "status", progress++, 100, false, out bcanceled);
                    if (progress == 100)
                    {
                        progress = 0;
                    }
                    if (bcanceled)
                    {
                        break;
                    }
                    Utilities.OutputCommandString(string.Format("ParentID={0}, WorkItemID={1}, Level={2}", tag.tParentID, tag.tWorkItemID, tag.tlevel));
                }
            }
            else
            {
                locidx = 1;
                foreach (WorkItem wi in query.RunQuery())
                {
                    strb.Clear();
                    string stratt;
                    foreach (Attachment att in wi.Attachments)
                    {
                        strb.Append(att.Name + "~" + att.Uri.ToString() + ";");
                    }
                    stratt = strb.ToString();
                    Utilities.OutputCommandString(stratt);

                    string witype = wi[CoreFieldReferenceNames.WorkItemType].ToString();
                    string wiid   = wi[CoreFieldReferenceNames.Id].ToString();
                    lqdata.Add(new[] { stratt, "0",
                                       (locidx++).ToString(),
                                       witype,
                                       wiid,
                                       wi[CoreFieldReferenceNames.Title].ToString(),
                                       wi[CoreFieldReferenceNames.Description].ToString() });

                    dlg.UpdateProgress("Exporting Work Item query to Microsoft Word document", "Parsing " + witype + " #" + wiid, "status", progress++, 100, false, out bcanceled);
                    if (progress == 100)
                    {
                        progress = 0;
                    }
                    if (bcanceled)
                    {
                        break;
                    }
                }
            }

            qdata = lqdata.ToArray();

            return(false);
        }
Ejemplo n.º 24
0
        private void TrialAndErrorRemovalThreadFunc(EnvDTE.Document document, TrialAndErrorRemovalOptionsPage settings,
                                                    Formatter.IncludeLineInfo[] includeLines, IVsThreadedWaitDialog2 progressDialog, ITextBuffer textBuffer)
        {
            int  numRemovedIncludes = 0;
            bool canceled           = false;

            try
            {
                int currentProgressStep = 0;

                // For ever include line..
                foreach (Formatter.IncludeLineInfo line in includeLines)
                {
                    // If we are working from top to bottom, the line number may have changed!
                    int currentLine = line.LineNumber;
                    if (settings.RemovalOrder == TrialAndErrorRemovalOptionsPage.IncludeRemovalOrder.TopToBottom)
                    {
                        currentLine -= numRemovedIncludes;
                    }

                    // Update progress.
                    string waitMessage  = $"Removing #includes from '{document.Name}'";
                    string progressText = $"Trying to remove '{line.IncludeContent}' ...";
                    progressDialog.UpdateProgress(
                        szUpdatedWaitMessage: waitMessage,
                        szProgressText: progressText,
                        szStatusBarText: "Running Trial & Error Removal - " + waitMessage + " - " + progressText,
                        iCurrentStep: currentProgressStep + 1,
                        iTotalSteps: includeLines.Length + 1,
                        fDisableCancel: false,
                        pfCanceled: out canceled);
                    if (canceled)
                    {
                        break;
                    }

                    ++currentProgressStep;

                    // Remove include - this needs to be done on the main thread.
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        using (var edit = textBuffer.CreateEdit())
                        {
                            if (settings.KeepLineBreaks)
                            {
                                edit.Delete(edit.Snapshot.Lines.ElementAt(currentLine).Extent);
                            }
                            else
                            {
                                edit.Delete(edit.Snapshot.Lines.ElementAt(currentLine).ExtentIncludingLineBreak);
                            }
                            edit.Apply();
                        }
                        outputWaitEvent.Set();
                    });
                    outputWaitEvent.WaitOne();

                    // Compile - In rare cases VS tells us that we are still building which should not be possible because we have received OnBuildFinished
                    // As a workaround we just try again a few times.
                    {
                        const int maxNumCompileAttempts = 3;
                        for (int numCompileFails = 0; numCompileFails < maxNumCompileAttempts; ++numCompileFails)
                        {
                            try
                            {
                                VSUtils.VCUtils.CompileSingleFile(document);
                            }
                            catch (Exception e)
                            {
                                Output.Instance.WriteLine("Compile Failed:\n{0}", e);

                                if (numCompileFails == maxNumCompileAttempts - 1)
                                {
                                    document.Undo();
                                    throw e;
                                }
                                else
                                {
                                    // Try again.
                                    System.Threading.Thread.Sleep(100);
                                    continue;
                                }
                            }
                            break;
                        }
                    }

                    // Wait till woken.
                    bool noTimeout = outputWaitEvent.WaitOne(timeoutMS);

                    // Undo removal if compilation failed.
                    if (!noTimeout || !lastBuildSuccessful)
                    {
                        Output.Instance.WriteLine("Could not remove #include: '{0}'", line.IncludeContent);
                        document.Undo();
                        if (!noTimeout)
                        {
                            Output.Instance.ErrorMsg("Compilation of {0} timeouted!", document.Name);
                            break;
                        }
                    }
                    else
                    {
                        Output.Instance.WriteLine("Successfully removed #include: '{0}'", line.IncludeContent);
                        ++numRemovedIncludes;
                    }
                }
            }
            catch (Exception ex)
            {
                Output.Instance.WriteLine("Unexpected error: {0}", ex);
            }
            finally
            {
                Application.Current.Dispatcher.Invoke(() => OnTrialAndErrorRemovalDone(progressDialog, document, numRemovedIncludes, canceled));
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private async void Execute(object sender, EventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            string                message           = string.Format(CultureInfo.CurrentCulture, "Inside {0}.MenuItemCallback()", this.GetType().FullName);
            SettingsManager       settingsManager   = new ShellSettingsManager((IServiceProvider)ServiceProvider);
            WritableSettingsStore userSettingsStore = settingsManager.GetWritableSettingsStore(SettingsScope.UserSettings);
            String                serverUrl         = userSettingsStore.GetString("ScantistSCA", "ServerURL", "https://api.scantist.io/");
            String                token             = userSettingsStore.GetString("ScantistSCA", "Token", "");
            String                projectName       = userSettingsStore.GetString("ScantistSCA", "ProjectName", "");

            ProjectDetailWindow projectDetailWindow = new ProjectDetailWindow();

            projectDetailWindow.ServerUrl   = serverUrl;
            projectDetailWindow.Token       = token;
            projectDetailWindow.ProjectName = projectName;
            projectDetailWindow.ShowModal();

            String ServerUrl   = projectDetailWindow.ServerUrl;
            String Token       = projectDetailWindow.Token;
            String ProjectName = projectDetailWindow.ProjectName;
            String FilePath    = projectDetailWindow.txtFileName.Text;

            if (projectDetailWindow.DialogResult.GetValueOrDefault(false))
            {
                var dialogFactory = await ServiceProvider.GetServiceAsync(typeof(SVsThreadedWaitDialogFactory)).ConfigureAwait(false) as IVsThreadedWaitDialogFactory;

                IVsThreadedWaitDialog2 dialog = null;
                if (dialogFactory != null)
                {
                    dialogFactory.CreateInstance(out dialog);
                }

                if (dialog != null && dialog.StartWaitDialog(
                        "Scantist SCA", "Retrieving the project dependency",
                        "We are getting there soon...", null,
                        "ScantistSCA is running...",
                        0, false,
                        true) == VSConstants.S_OK)
                {
                    if (!userSettingsStore.CollectionExists("ScantistSCA"))
                    {
                        userSettingsStore.CreateCollection("ScantistSCA");
                    }

                    userSettingsStore.SetString("ScantistSCA", "ServerURL", ServerUrl);
                    userSettingsStore.SetString("ScantistSCA", "Token", Token);
                    userSettingsStore.SetString("ScantistSCA", "ProjectName", ProjectName);

                    CommandParameters commandParameters = new CommandParameters();
                    commandParameters.parseCommandLine(new string[11] {
                        "-t", Token, "-serverUrl",
                        ServerUrl, "-scanType", "source_code", "-f", Path.GetDirectoryName(FilePath),
                        "-project_name", ProjectName, "--debug"
                    });
                    int scanID = new Application().run(commandParameters);

                    if (scanID == 0)
                    {
                        VsShellUtilities.ShowMessageBox(
                            this.package,
                            "Cannot trigger SCA scan. Please check log file for detail.",
                            "Error",
                            OLEMSGICON.OLEMSGICON_INFO,
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                    }
                    else
                    {
                        VsShellUtilities.ShowMessageBox(
                            this.package,
                            "Scan " + scanID + " is successfully created.",
                            "Completed",
                            OLEMSGICON.OLEMSGICON_INFO,
                            OLEMSGBUTTON.OLEMSGBUTTON_OK,
                            OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

                        userSettingsStore.SetString("ScantistSCA", "ScanID", scanID.ToString());

                        await this.package.JoinableTaskFactory.RunAsync(async delegate
                        {
                            ToolWindowPane window = await this.package.ShowToolWindowAsync(typeof(ComponentResult), 0, true, this.package.DisposalToken);
                            if ((null == window) || (null == window.Frame))
                            {
                                throw new NotSupportedException("Cannot create tool window");
                            }
                        });
                    }
                }
                int usercancel;
                dialog.EndWaitDialog(out usercancel);
            }
        }
Ejemplo n.º 26
0
        private void RestorePackagesOrCheckForMissingPackages()
        {
            var waitDialogFactory = ServiceLocator.GetGlobalService<SVsThreadedWaitDialogFactory, IVsThreadedWaitDialogFactory>();
            waitDialogFactory.CreateInstance(out _waitDialog);

            try
            {                
                if (IsConsentGranted())
                {
                    RestorePackages();
                }
                else
                {
                    _waitDialog.StartWaitDialog(
                        VsResources.DialogTitle,
                        Resources.RestoringPackages,
                        String.Empty,
                        varStatusBmpAnim: null,
                        szStatusBarText: null,
                        iDelayToShowDialog: 0,
                        fIsCancelable: true,
                        fShowMarqueeProgress: true);
                    CheckForMissingPackages();
                }
            }
            finally
            {
                int canceled;
                _waitDialog.EndWaitDialog(out canceled);
                _waitDialog = null;
            }
        }
Ejemplo n.º 27
0
        public override void NextBtnCommandAction(Object param)
        {
            switch (CurrentUiStepId)
            {
            case 0:
                CurrentUiStepId = 1;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                SaveBtnEnabled  = false;
                if (SelectDbContextUC == null)
                {
                    SelectDbContextViewModel dataContext = new SelectDbContextViewModel(Dte);
                    dataContext.UiCommandButtonVisibility = Visibility.Collapsed;
                    dataContext.UiCommandCaption3         = "NameSpace: " + (InvitationUC.DataContext as InvitationViewModel).DefaultProjectNameSpace;
                    string folder = (InvitationUC.DataContext as InvitationViewModel).DestinationFolder;
                    if (!string.IsNullOrEmpty(folder))
                    {
                        dataContext.UiCommandCaption3 = dataContext.UiCommandCaption3 + "." + folder.Replace("\\", ".");
                    }
                    SelectDbContextUC = new UserControlSelectSource(dataContext);
                    dataContext.IsReady.IsReadyEvent += CallBack_IsReady;
                }
                (SelectDbContextUC.DataContext as SelectDbContextViewModel).DoAnaliseDbContext();
                this.CurrentUserControl = SelectDbContextUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            case 1:
                CurrentUiStepId = 2;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                if (CreateWebApiUC == null)
                {
                    CreateWebApiViewModel dataContext = new CreateWebApiViewModel(Dte);
                    dataContext.IsReady.IsReadyEvent      += CallBack_IsReady;
                    dataContext.DestinationProject         = (InvitationUC.DataContext as InvitationViewModel).DestinationProject;
                    dataContext.DefaultProjectNameSpace    = (InvitationUC.DataContext as InvitationViewModel).DefaultProjectNameSpace;
                    dataContext.DestinationFolder          = (InvitationUC.DataContext as InvitationViewModel).DestinationFolder;
                    dataContext.IsWebServiceEditable       = false;
                    dataContext.UIFormPropertiesVisibility = Visibility.Visible;
                    dataContext.UIListPropertiesVisibility = Visibility.Visible;

                    CreateWebApiUC = new UserControlCreateWebApi(dataContext);
                }
                (CreateWebApiUC.DataContext as CreateWebApiViewModel).SelectedDbContext =
                    (SelectDbContextUC.DataContext as SelectDbContextViewModel).SelectedCodeElement;
                (CreateWebApiUC.DataContext as CreateWebApiViewModel).CheckIsReady();
                this.CurrentUserControl = CreateWebApiUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            case 2:
                bool   hasUIFormPropertiesError  = false;
                string textUIFormPropertiesError = "";
                foreach (ModelViewUIFormProperty modelViewUIFormProperty in (CreateWebApiUC.DataContext as CreateWebApiViewModel).UIFormProperties)
                {
                    if (
                        ((modelViewUIFormProperty.InputTypeWhenAdd == InputTypeEnum.Combo) ||
                         (modelViewUIFormProperty.InputTypeWhenAdd == InputTypeEnum.SearchDialog) ||
                         (modelViewUIFormProperty.InputTypeWhenAdd == InputTypeEnum.Typeahead)) &&
                        string.IsNullOrEmpty(modelViewUIFormProperty.ForeignKeyNameChain)
                        )
                    {
                        hasUIFormPropertiesError   = true;
                        textUIFormPropertiesError += "\n InputTypeWhenAdd for UIFormProperty named [" + modelViewUIFormProperty.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                        textUIFormPropertiesError += "\n but ForeignKeyNameChain is empty for this property.";
                        textUIFormPropertiesError += "\n Generators will not work correctly.";
                        textUIFormPropertiesError += "\n ";
                    }
                    if (
                        ((modelViewUIFormProperty.InputTypeWhenUpdate == InputTypeEnum.Combo) ||
                         (modelViewUIFormProperty.InputTypeWhenUpdate == InputTypeEnum.SearchDialog) ||
                         (modelViewUIFormProperty.InputTypeWhenUpdate == InputTypeEnum.Typeahead)) &&
                        string.IsNullOrEmpty(modelViewUIFormProperty.ForeignKeyNameChain)
                        )
                    {
                        hasUIFormPropertiesError   = true;
                        textUIFormPropertiesError += "\n InputTypeWhenUpdate for UIFormProperty named [" + modelViewUIFormProperty.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                        textUIFormPropertiesError += "\n but ForeignKeyNameChain is empty for this property.";
                        textUIFormPropertiesError += "\n Generators will not work correctly.";
                        textUIFormPropertiesError += "\n ";
                    }
                    if (
                        ((modelViewUIFormProperty.InputTypeWhenDelete == InputTypeEnum.Combo) ||
                         (modelViewUIFormProperty.InputTypeWhenDelete == InputTypeEnum.SearchDialog) ||
                         (modelViewUIFormProperty.InputTypeWhenDelete == InputTypeEnum.Typeahead)) &&
                        string.IsNullOrEmpty(modelViewUIFormProperty.ForeignKeyNameChain)
                        )
                    {
                        hasUIFormPropertiesError   = true;
                        textUIFormPropertiesError += "\n InputTypeWhenUpdate for UIFormProperty named [" + modelViewUIFormProperty.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                        textUIFormPropertiesError += "\n but ForeignKeyNameChain is empty for this property.";
                        textUIFormPropertiesError += "\n Generators will not work correctly.";
                        textUIFormPropertiesError += "\n ";
                    }


                    if (
                        ((modelViewUIFormProperty.InputTypeWhenAdd == InputTypeEnum.Combo) ||
                         (modelViewUIFormProperty.InputTypeWhenAdd == InputTypeEnum.SearchDialog) ||
                         (modelViewUIFormProperty.InputTypeWhenAdd == InputTypeEnum.Typeahead)) &&
                        (!modelViewUIFormProperty.IsShownInView)
                        )
                    {
                        hasUIFormPropertiesError   = true;
                        textUIFormPropertiesError += "\n InputTypeWhenAdd for UIFormProperty named [" + modelViewUIFormProperty.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                        textUIFormPropertiesError += "\n but IsShown is not checked.";
                        textUIFormPropertiesError += "\n Generators will not work correctly.";
                        textUIFormPropertiesError += "\n ";
                    }
                    if (
                        ((modelViewUIFormProperty.InputTypeWhenUpdate == InputTypeEnum.Combo) ||
                         (modelViewUIFormProperty.InputTypeWhenUpdate == InputTypeEnum.SearchDialog) ||
                         (modelViewUIFormProperty.InputTypeWhenUpdate == InputTypeEnum.Typeahead)) &&
                        (!modelViewUIFormProperty.IsShownInView)
                        )
                    {
                        hasUIFormPropertiesError   = true;
                        textUIFormPropertiesError += "\n InputTypeWhenUpdate for UIFormProperty named [" + modelViewUIFormProperty.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                        textUIFormPropertiesError += "\n but IsShown is not checked.";
                        textUIFormPropertiesError += "\n Generators will not work correctly.";
                        textUIFormPropertiesError += "\n ";
                    }
                    if (
                        ((modelViewUIFormProperty.InputTypeWhenDelete == InputTypeEnum.Combo) ||
                         (modelViewUIFormProperty.InputTypeWhenDelete == InputTypeEnum.SearchDialog) ||
                         (modelViewUIFormProperty.InputTypeWhenDelete == InputTypeEnum.Typeahead)) &&
                        (!modelViewUIFormProperty.IsShownInView)
                        )
                    {
                        hasUIFormPropertiesError   = true;
                        textUIFormPropertiesError += "\n InputTypeWhenUpdate for UIFormProperty named [" + modelViewUIFormProperty.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                        textUIFormPropertiesError += "\n but IsShown is not checked.";
                        textUIFormPropertiesError += "\n Generators will not work correctly.";
                        textUIFormPropertiesError += "\n ";
                    }
                }
                int uIFormPropertiesCount = (CreateWebApiUC.DataContext as CreateWebApiViewModel).UIFormProperties.Count;
                for (int inpTp = 1; inpTp < 4; inpTp++)
                {
                    for (int i = 0; i < uIFormPropertiesCount - 1; i++)
                    {
                        ModelViewUIFormProperty modelViewUIFormProperty =
                            (CreateWebApiUC.DataContext as CreateWebApiViewModel).UIFormProperties[i];
                        if (string.IsNullOrEmpty(modelViewUIFormProperty.ForeignKeyNameChain))
                        {
                            continue;
                        }
                        if (inpTp == 1)
                        {
                            if (!((modelViewUIFormProperty.InputTypeWhenAdd == InputTypeEnum.Combo) ||
                                  (modelViewUIFormProperty.InputTypeWhenAdd == InputTypeEnum.Typeahead) ||
                                  (modelViewUIFormProperty.InputTypeWhenAdd == InputTypeEnum.SearchDialog)))
                            {
                                continue;
                            }
                        }
                        else if (inpTp == 2)
                        {
                            if (!((modelViewUIFormProperty.InputTypeWhenUpdate == InputTypeEnum.Combo) ||
                                  (modelViewUIFormProperty.InputTypeWhenUpdate == InputTypeEnum.Typeahead) ||
                                  (modelViewUIFormProperty.InputTypeWhenUpdate == InputTypeEnum.SearchDialog)))
                            {
                                continue;
                            }
                        }
                        else
                        {
                            if (!((modelViewUIFormProperty.InputTypeWhenDelete == InputTypeEnum.Combo) ||
                                  (modelViewUIFormProperty.InputTypeWhenDelete == InputTypeEnum.Typeahead) ||
                                  (modelViewUIFormProperty.InputTypeWhenDelete == InputTypeEnum.SearchDialog)))
                            {
                                continue;
                            }
                        }
                        for (int k = i + 1; k < uIFormPropertiesCount; k++)
                        {
                            ModelViewUIFormProperty modelViewUIFormProperty2 =
                                (CreateWebApiUC.DataContext as CreateWebApiViewModel).UIFormProperties[k];
                            if (string.IsNullOrEmpty(modelViewUIFormProperty2.ForeignKeyNameChain))
                            {
                                continue;
                            }
                            if (modelViewUIFormProperty2.ForeignKeyNameChain != modelViewUIFormProperty.ForeignKeyNameChain)
                            {
                                continue;
                            }
                            if (inpTp == 1)
                            {
                                if ((modelViewUIFormProperty2.InputTypeWhenAdd == InputTypeEnum.Combo) ||
                                    (modelViewUIFormProperty2.InputTypeWhenAdd == InputTypeEnum.Typeahead) ||
                                    (modelViewUIFormProperty2.InputTypeWhenAdd == InputTypeEnum.SearchDialog))
                                {
                                    hasUIFormPropertiesError   = true;
                                    textUIFormPropertiesError += "\n InputTypeWhenAdd for UIFormProperty named [" + modelViewUIFormProperty.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                                    textUIFormPropertiesError += "\n InputTypeWhenAdd for UIFormProperty named [" + modelViewUIFormProperty2.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                                    textUIFormPropertiesError += "\n Both properties have the same ForeignKeyNameChain =[" + modelViewUIFormProperty.ForeignKeyNameChain + "].";
                                    textUIFormPropertiesError += "\n For InputTypeWhenAdd only one property for each ForeignKeyNameChain can be set to one of the values (Combo, SearchDialog, Typeahead).";
                                    textUIFormPropertiesError += "\n Generators will not work correctly.";
                                    textUIFormPropertiesError += "\n ";
                                }
                            }
                            else if (inpTp == 2)
                            {
                                if ((modelViewUIFormProperty2.InputTypeWhenUpdate == InputTypeEnum.Combo) ||
                                    (modelViewUIFormProperty2.InputTypeWhenUpdate == InputTypeEnum.Typeahead) ||
                                    (modelViewUIFormProperty2.InputTypeWhenUpdate == InputTypeEnum.SearchDialog))
                                {
                                    textUIFormPropertiesError += "\n InputTypeWhenUpdate for UIFormProperty named [" + modelViewUIFormProperty.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                                    textUIFormPropertiesError += "\n InputTypeWhenUpdate for UIFormProperty named [" + modelViewUIFormProperty2.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                                    textUIFormPropertiesError += "\n Both properties have the same ForeignKeyNameChain =[" + modelViewUIFormProperty.ForeignKeyNameChain + "].";
                                    textUIFormPropertiesError += "\n For InputTypeWhenUpdate only one property for each ForeignKeyNameChain can be set to one of the values (Combo, SearchDialog, Typeahead).";
                                    textUIFormPropertiesError += "\n Generators will not work correctly.";
                                    textUIFormPropertiesError += "\n ";
                                }
                            }
                            else
                            {
                                if ((modelViewUIFormProperty2.InputTypeWhenDelete == InputTypeEnum.Combo) ||
                                    (modelViewUIFormProperty2.InputTypeWhenDelete == InputTypeEnum.Typeahead) ||
                                    (modelViewUIFormProperty2.InputTypeWhenDelete == InputTypeEnum.SearchDialog))
                                {
                                    textUIFormPropertiesError += "\n InputTypeWhenDelete for UIFormProperty named [" + modelViewUIFormProperty.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                                    textUIFormPropertiesError += "\n InputTypeWhenDelete for UIFormProperty named [" + modelViewUIFormProperty2.ViewPropertyName + "] was set to one of the values (Combo, SearchDialog, Typeahead)";
                                    textUIFormPropertiesError += "\n Both properties have the same ForeignKeyNameChain =[" + modelViewUIFormProperty.ForeignKeyNameChain + "].";
                                    textUIFormPropertiesError += "\n For InputTypeWhenDelete only one property for each ForeignKeyNameChain can be set to one of the values (Combo, SearchDialog, Typeahead).";
                                    textUIFormPropertiesError += "\n Generators will not work correctly.";
                                    textUIFormPropertiesError += "\n ";
                                }
                            }
                        }
                    }
                }


                if (hasUIFormPropertiesError)
                {
                    textUIFormPropertiesError += "\n Would you like to continue ?";
                    if (MessageBox.Show(textUIFormPropertiesError, "Error", MessageBoxButton.YesNo, MessageBoxImage.Warning) != MessageBoxResult.Yes)
                    {
                        return;
                    }
                }
                CurrentUiStepId = 3;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                if (SelectFolderUC == null)
                {
                    string TemplatesFld = TemplatePathHelper.GetTemplatePath();
                    SelectFolderViewModel dataContext = new SelectFolderViewModel(Dte, TextTemplating, DialogFactory, (CreateWebApiUC.DataContext as CreateWebApiViewModel).SelectedDbContext, TemplatesFld, "JavaScriptsTmplst", "BatchJavaScriptsTmplst");
                    dataContext.DestinationProjectRootFolder     = (InvitationUC.DataContext as InvitationViewModel).DestinationProjectRootFolder;
                    dataContext.DestinationFolder                = (InvitationUC.DataContext as InvitationViewModel).DestinationFolder;
                    dataContext.ContextItemViewName              = (CreateWebApiUC.DataContext as CreateWebApiViewModel).ContextItemViewName;
                    dataContext.DestinationProjectName           = (InvitationUC.DataContext as InvitationViewModel).DestinationProject;
                    dataContext.DestinationProject               = this.DestinationProject;
                    dataContext.DefaultProjectNameSpace          = (InvitationUC.DataContext as InvitationViewModel).DefaultProjectNameSpace;
                    dataContext.IsReady.IsReadyEvent            += CallBack_IsReady;
                    dataContext.OnContextChanged.ContextChanged += OnContextChanged;
                    SelectFolderUC = new UserControlSelectFolder(dataContext);
                }
                (SelectFolderUC.DataContext as SelectFolderViewModel).SerializableDbContext =
                    (CreateWebApiUC.DataContext as CreateWebApiViewModel).SerializableDbContext;
                (SelectFolderUC.DataContext as SelectFolderViewModel).SelectedModel =
                    (CreateWebApiUC.DataContext as CreateWebApiViewModel).SelectedModel;

                (SelectFolderUC.DataContext as SelectFolderViewModel).UIFormProperties = (CreateWebApiUC.DataContext as CreateWebApiViewModel).UIFormProperties;
                (SelectFolderUC.DataContext as SelectFolderViewModel).UIListProperties = (CreateWebApiUC.DataContext as CreateWebApiViewModel).UIListProperties;

                (SelectFolderUC.DataContext as SelectFolderViewModel).CheckIsReady();
                this.CurrentUserControl = SelectFolderUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            case 3:
                CurrentUiStepId = 4;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                if (T4EditorUC == null)
                {
                    string            templatePath = Path.Combine((SelectFolderUC.DataContext as SelectFolderViewModel).T4RootFolder, (SelectFolderUC.DataContext as SelectFolderViewModel).T4SelectedFolder);
                    T4EditorViewModel dataContext  = new T4EditorViewModel(templatePath);
                    dataContext.IsReady.IsReadyEvent += CallBack_IsReady;
                    T4EditorUC = new UserControlT4Editor(dataContext);
                }
                (T4EditorUC.DataContext as T4EditorViewModel).T4TemplateFolder =
                    Path.Combine((SelectFolderUC.DataContext as SelectFolderViewModel).T4RootFolder, (SelectFolderUC.DataContext as SelectFolderViewModel).T4SelectedFolder);
                (T4EditorUC.DataContext as T4EditorViewModel).CheckIsReady();
                this.CurrentUserControl = T4EditorUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            case 4:
                CurrentUiStepId = 5;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = true;
                IVsThreadedWaitDialog2 aDialog = null;
                bool aDialogStarted            = false;
                if (this.DialogFactory != null)
                {
                    this.DialogFactory.CreateInstance(out aDialog);
                    if (aDialog != null)
                    {
                        aDialogStarted = aDialog.StartWaitDialog("Generation started", "VS is Busy", "Please wait", null, "Generation started", 0, false, true) == VSConstants.S_OK;
                    }
                }

                if (GenerateUC == null)
                {
                    GenerateCommonStaffViewModel dataContext = new GenerateCommonStaffViewModel();
                    dataContext.IsReady.IsReadyEvent += GenerateWebApiViewModel_IsReady;
                    GenerateUC = new UserControlGenerate(dataContext);
                }

                (GenerateUC.DataContext as GenerateCommonStaffViewModel).GenText = (T4EditorUC.DataContext as T4EditorViewModel).T4TempateText;

                try
                {
                    (GenerateUC.DataContext as GenerateCommonStaffViewModel)
                    .DoGenerateViewModel(Dte, TextTemplating,
                                         (T4EditorUC.DataContext as T4EditorViewModel).T4TempatePath,
                                         (CreateWebApiUC.DataContext as CreateWebApiViewModel).SerializableDbContext,
                                         (CreateWebApiUC.DataContext as CreateWebApiViewModel).GetSelectedModelCommonShallowCopy(
                                             (SelectFolderUC.DataContext as SelectFolderViewModel).T4SelectedFolder,
                                             (SelectFolderUC.DataContext as SelectFolderViewModel).FileName,
                                             (T4EditorUC.DataContext as T4EditorViewModel).T4SelectedTemplate
                                             ),
                                         (InvitationUC.DataContext as InvitationViewModel).DefaultProjectNameSpace
                                         );
                    if (aDialogStarted)
                    {
                        int iOut;
                        aDialog.EndWaitDialog(out iOut);
                    }
                }
                catch (Exception e)
                {
                    if (aDialogStarted)
                    {
                        int iOut;
                        aDialog.EndWaitDialog(out iOut);
                    }
                    MessageBox.Show("Error: " + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    this.CurrentUserControl = GenerateUC;
                    this.OnPropertyChanged("CurrentUserControl");
                }
                break;

            case 5:
                CurrentUiStepId = 2;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                SaveBtnEnabled  = false;
                (CreateWebApiUC.DataContext as CreateWebApiViewModel).CheckIsReady();
                this.CurrentUserControl = CreateWebApiUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            default:
                break;
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Menus the item callback.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public static void TeamExpQueryCallback(object sender, EventArgs e)
        {
            var origCursor = Cursor.Current;

            Cursor.Current = Cursors.WaitCursor;

            //IntPtr hier;
            //uint itemid;
            //IVsMultiItemSelect dummy;
            //string canonicalName;
            bool   bcanceled;
            int    icanceled;
            string OperationCaption    = "Exporting Work Item query to Microsoft Word document";
            IVsThreadedWaitDialog2 dlg = null;

            try
            {
                dlg = Utilities.CreateThreadedWaitDialog(OperationCaption, "Parsing query...", "status", 100);
                dlg.UpdateProgress(OperationCaption, "Parsing query...", "status", 1, 100, false, out bcanceled);

                //Utilities.vsTeamExp.TeamExplorerWindow.GetCurrentSelection(out hier, out itemid, out dummy);
                //IVsHierarchy hierarchy = (IVsHierarchy)Marshal.GetObjectForIUnknown(hier);
                //Marshal.Release(hier);

                //hierarchy.GetProperty(itemid, (int)__VSHPROPID.VSHPROPID_ExtSelectedItem, out res);
                //MessageBox.Show(res.GetType().ToString());

                //hierarchy.GetCanonicalName(itemid, out canonicalName);

                /*
                 * string[] tokens = canonicalName.Split('/');
                 * string ProjectName = tokens[1];
                 * var proj = Utilities.wistore.Projects[ProjectName];
                 *
                 * QueryItem qItem = proj.QueryHierarchy;
                 *
                 * int currentTokenIndex = 2;
                 * while (currentTokenIndex < tokens.Length)
                 * {
                 *  qItem = (qItem as QueryFolder)[tokens[currentTokenIndex]];
                 *  currentTokenIndex++;
                 * }*/

                var WIQueriesPageExt = Utilities.teamExplorer.CurrentPage.GetService <IWorkItemQueriesExt>();
                var qItem            = WIQueriesPageExt.SelectedQueryItems.First();

                //string[] qheader;
                string[][] qdata;
                bcanceled = ExecuteQueryLimitedFields(dlg, qItem as QueryDefinition, qItem.Project.Name, out qdata);
                dlg.UpdateProgress(OperationCaption, "Creating new Word document...", "status", 1, 100, false, out bcanceled);

                CreateWordDocParagraph((qItem as QueryDefinition).Name, qdata, dlg);

                Cursor.Current = origCursor;
                dlg.EndWaitDialog(out icanceled);
            }
            catch (Exception ex)
            {
                Cursor.Current = origCursor;
                if (dlg != null)
                {
                    dlg.EndWaitDialog(out icanceled);
                }
                Utilities.OutputCommandString(ex.ToString());
                MessageBox.Show(ex.InnerException != null ? ex.InnerException.Message : ex.Message, Utilities.AppTitle, MessageBoxButtons.OK);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        protected override async Task MenuItemCallback(object sender, EventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var settingsIwyu = (IncludeWhatYouUseOptionsPage)Package.GetDialogPage(typeof(IncludeWhatYouUseOptionsPage));

            Output.Instance.Clear();

            var document = VSUtils.GetDTE().ActiveDocument;

            if (document == null)
            {
                Output.Instance.WriteLine("No active document!");
                return;
            }
            var project = document.ProjectItem?.ContainingProject;

            if (project == null)
            {
                Output.Instance.WriteLine("The document {0} is not part of a project.", document.Name);
                return;
            }

            var dialogFactory = ServiceProvider.GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;

            if (dialogFactory == null)
            {
                Output.Instance.WriteLine("Failed to get IVsThreadedWaitDialogFactory service.");
                return;
            }

            await OptionalDownloadOrUpdate(settingsIwyu, dialogFactory);

            // We should really have it now, but just in case our update or download method screwed up.
            if (!File.Exists(settingsIwyu.ExecutablePath))
            {
                await Output.Instance.ErrorMsg("Unexpected error: Can't find include-what-you-use.exe after download/update.");

                return;
            }
            checkedForUpdatesThisSession = true;

            // Save all documents.
            try
            {
                document.DTE.Documents.SaveAll();
            }
            catch (Exception saveException)
            {
                Output.Instance.WriteLine("Failed to get save all documents: {0}", saveException);
            }

            // Start wait dialog.
            {
                IVsThreadedWaitDialog2 dialog = null;
                dialogFactory.CreateInstance(out dialog);
                dialog?.StartWaitDialog("Include Toolbox", "Running include-what-you-use", null, null, "Running include-what-you-use", 0, false, true);

                string output = await IWYU.RunIncludeWhatYouUse(document.FullName, project, settingsIwyu);

                if (settingsIwyu.ApplyProposal && output != null)
                {
                    var settingsFormatting = (FormatterOptionsPage)Package.GetDialogPage(typeof(FormatterOptionsPage));
                    await IWYU.Apply(output, settingsIwyu.RunIncludeFormatter, settingsFormatting);
                }

                dialog?.EndWaitDialog();
            }
        }
Ejemplo n.º 30
0
        public override void NextBtnCommandAction(Object param)
        {
            switch (CurrentUiStepId)
            {
            case 0:
                CurrentUiStepId = 1;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                SaveBtnEnabled  = false;
                if (SelectDbContextUC == null)
                {
                    SelectDbContextViewModel dataContext = new SelectDbContextViewModel(Dte);
                    dataContext.UiCommandButtonVisibility = Visibility.Collapsed;
                    dataContext.UiCommandCaption3         = "NameSpace: " + (InvitationUC.DataContext as InvitationViewModel).DefaultProjectNameSpace;
                    string folder = (InvitationUC.DataContext as InvitationViewModel).DestinationFolder;
                    if (!string.IsNullOrEmpty(folder))
                    {
                        dataContext.UiCommandCaption3 = dataContext.UiCommandCaption3 + "." + folder.Replace("\\", ".");
                    }
                    SelectDbContextUC = new UserControlSelectSource(dataContext);
                    dataContext.IsReady.IsReadyEvent += SelectDbContextViewModel_IsReady;
                }
                (SelectDbContextUC.DataContext as SelectDbContextViewModel).DoAnaliseDbContext();
                this.CurrentUserControl = SelectDbContextUC;
                this.OnPropertyChanged("CurrentUserControl");


                break;

            case 1:
                CurrentUiStepId = 2;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                SaveBtnEnabled  = false;
                if (SelectSourceEntityUC == null)
                {
                    SelectEntityForGivenDbContextViewModel dataContext = new SelectEntityForGivenDbContextViewModel(Dte);
                    dataContext.UiCommandButtonVisibility = Visibility.Collapsed;
                    dataContext.IsReady.IsReadyEvent     += SelectEntityForGivenDbContextViewModel_IsReady;
                    SelectSourceEntityUC = new UserControlSelectSource(dataContext);
                }
                (SelectSourceEntityUC.DataContext as SelectEntityForGivenDbContextViewModel).SelectedDbContext =
                    (SelectDbContextUC.DataContext as SelectDbContextViewModel).SelectedCodeElement;
                (SelectSourceEntityUC.DataContext as SelectEntityForGivenDbContextViewModel).CheckIsReady();
                OnDbContextChanged();
                this.CurrentUserControl = SelectSourceEntityUC;
                this.OnPropertyChanged("CurrentUserControl");

                break;

            case 2:
                CurrentUiStepId = 3;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                SaveBtnEnabled  = false;
                if (SelectExistingUC == null)
                {
                    SelectExistingViewModel dataContext = new SelectExistingViewModel(Dte);
                    dataContext.IsReady.IsReadyEvent += SelectEntityForGivenDbContextViewModel_IsReady;
                    SelectExistingUC = new UserControlSelectExisting(dataContext);
                }
                (SelectExistingUC.DataContext as SelectExistingViewModel).CurrentDbContext = CurrentDbContext;
                (SelectExistingUC.DataContext as SelectExistingViewModel).SelectedEntity   =
                    (SelectSourceEntityUC.DataContext as SelectEntityForGivenDbContextViewModel).SelectedCodeElement;

                (SelectExistingUC.DataContext as SelectExistingViewModel).DestinationProject      = (InvitationUC.DataContext as InvitationViewModel).DestinationProject;
                (SelectExistingUC.DataContext as SelectExistingViewModel).DefaultProjectNameSpace = (InvitationUC.DataContext as InvitationViewModel).DefaultProjectNameSpace;
                (SelectExistingUC.DataContext as SelectExistingViewModel).DestinationFolder       = (InvitationUC.DataContext as InvitationViewModel).DestinationFolder;
                (SelectExistingUC.DataContext as SelectExistingViewModel).DbSetProppertyName      = (SelectSourceEntityUC.DataContext as SelectEntityForGivenDbContextViewModel).SelectedProppertyName;

                (SelectExistingUC.DataContext as SelectExistingViewModel).DoAnalize();
                this.CurrentUserControl = SelectExistingUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            case 3:
                CurrentUiStepId = 4;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = true;
                SaveBtnEnabled  = false;
                if (CreateViewUC == null)
                {
                    CreateViewViewModel dataContext = new CreateViewViewModel(Dte);
                    dataContext.IsReady.IsReadyEvent   += SelectEntityForGivenDbContextViewModel_IsReady;
                    dataContext.DestinationProject      = (InvitationUC.DataContext as InvitationViewModel).DestinationProject;
                    dataContext.DefaultProjectNameSpace = (InvitationUC.DataContext as InvitationViewModel).DefaultProjectNameSpace;
                    dataContext.DestinationFolder       = (InvitationUC.DataContext as InvitationViewModel).DestinationFolder;
                    CreateViewUC = new UserControlCreateView(dataContext);
                }
                (CreateViewUC.DataContext as CreateViewViewModel).SelectedDbContext =
                    (SelectSourceEntityUC.DataContext as SelectEntityForGivenDbContextViewModel).SelectedDbContext;
                (CreateViewUC.DataContext as CreateViewViewModel).SelectedEntity =
                    (SelectSourceEntityUC.DataContext as SelectEntityForGivenDbContextViewModel).SelectedCodeElement;
                (CreateViewUC.DataContext as CreateViewViewModel).CurrentDbContext = CurrentDbContext;
                (CreateViewUC.DataContext as CreateViewViewModel).DestinationDbSetProppertyName =
                    (SelectSourceEntityUC.DataContext as SelectEntityForGivenDbContextViewModel).SelectedProppertyName;
                ModelViewSerializable srcModel = null;
                if ((SelectExistingUC.DataContext as SelectExistingViewModel).IsSelectExisting)
                {
                    srcModel = (SelectExistingUC.DataContext as SelectExistingViewModel).SelectedModel;
                }
                (CreateViewUC.DataContext as CreateViewViewModel).DoAnalize(srcModel);
                this.CurrentUserControl = CreateViewUC;
                this.OnPropertyChanged("CurrentUserControl");

                break;

            case 4:
                string checkErrorsText = (CreateViewUC.DataContext as CreateViewViewModel).SelectedModel.CheckCorrect();
                if (!string.IsNullOrEmpty(checkErrorsText))
                {
                    (CreateViewUC.DataContext as CreateViewViewModel).CheckErrorsText = checkErrorsText;
                    return;
                }

                CurrentUiStepId = 5;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = true;
                SaveBtnEnabled  = false;
                if (T4EditorUC == null)
                {
                    string            TemplatesFld = TemplatePathHelper.GetTemplatePath();
                    string            templatePath = Path.Combine(TemplatesFld, "ViewModelTmplst");
                    T4EditorViewModel dataContext  = new T4EditorViewModel(templatePath);
                    dataContext.IsReady.IsReadyEvent += T4EditorViewModel_IsReady;
                    T4EditorUC = new UserControlT4Editor(dataContext);
                }
                (T4EditorUC.DataContext as T4EditorViewModel).CheckIsReady();
                this.CurrentUserControl = T4EditorUC;
                this.OnPropertyChanged("CurrentUserControl");

                break;

            case 5:
                CurrentUiStepId = 6;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = false;
                IVsThreadedWaitDialog2 aDialog = null;
                bool aDialogStarted            = false;
                if (this.DialogFactory != null)
                {
                    this.DialogFactory.CreateInstance(out aDialog);
                    if (aDialog != null)
                    {
                        aDialogStarted = aDialog.StartWaitDialog("Generation started", "VS is Busy", "Please wait", null, "Generation started", 0, false, true) == VSConstants.S_OK;
                    }
                }

                if (GenerateUC == null)
                {
                    GenerateViewModel generateViewModel = new GenerateViewModel();
                    generateViewModel.IsReady.IsReadyEvent += GenerateViewModel_IsReady;
                    GenerateUC = new UserControlGenerate(generateViewModel);
                }
                (GenerateUC.DataContext as GenerateViewModel).GenText = (T4EditorUC.DataContext as T4EditorViewModel).T4TempateText;
                try
                {
                    (CreateViewUC.DataContext as CreateViewViewModel).SelectedModel.RootEntityDbContextPropertyName =
                        (CreateViewUC.DataContext as CreateViewViewModel).DestinationDbSetProppertyName;
                    (GenerateUC.DataContext as GenerateViewModel).DoGenerateViewModel(Dte, TextTemplating, null,
                                                                                      (T4EditorUC.DataContext as T4EditorViewModel).T4TempatePath,
                                                                                      (CreateViewUC.DataContext as CreateViewViewModel).SelectedModel);
                    NextBtnEnabled = true;
                    if (aDialogStarted)
                    {
                        int iOut;
                        aDialog.EndWaitDialog(out iOut);
                    }
                    MessageBox.Show(SuccessNotification, "Done", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception e)
                {
                    if (aDialogStarted)
                    {
                        int iOut;
                        aDialog.EndWaitDialog(out iOut);
                    }
                    MessageBox.Show("Error: " + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    this.CurrentUserControl = GenerateUC;
                    this.OnPropertyChanged("CurrentUserControl");
                }
                break;

            case 6:
                CurrentUiStepId = 7;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = true;
                SaveBtnEnabled  = false;
                if (T4EditorPageUC == null)
                {
                    string            TemplatesFld = TemplatePathHelper.GetTemplatePath();
                    string            templatePath = Path.Combine(TemplatesFld, "ViewPageModelTmplst");
                    T4EditorViewModel dataContext  = new T4EditorViewModel(templatePath);
                    dataContext.IsReady.IsReadyEvent += T4EditorViewModel_IsReady;
                    T4EditorPageUC = new UserControlT4Editor(dataContext);
                }
                (T4EditorPageUC.DataContext as T4EditorViewModel).CheckIsReady();
                this.CurrentUserControl = T4EditorPageUC;
                this.OnPropertyChanged("CurrentUserControl");
                break;

            case 7:
                CurrentUiStepId = 8;
                PrevBtnEnabled  = true;
                NextBtnEnabled  = true;
                IVsThreadedWaitDialog2 aaDialog = null;
                bool aaDialogStarted            = false;
                if (this.DialogFactory != null)
                {
                    this.DialogFactory.CreateInstance(out aaDialog);
                    if (aaDialog != null)
                    {
                        aaDialogStarted = aaDialog.StartWaitDialog("Generation started", "VS is Busy", "Please wait", null, "Generation started", 0, false, true) == VSConstants.S_OK;
                    }
                }
                if (GeneratePageUC == null)
                {
                    GenerateViewPageModel generateViewModel = new GenerateViewPageModel();
                    generateViewModel.IsReady.IsReadyEvent += GenerateViewModel_IsReady;
                    GeneratePageUC = new UserControlGenerate(generateViewModel);
                }
                (GeneratePageUC.DataContext as GenerateViewPageModel).GenText = (T4EditorPageUC.DataContext as T4EditorViewModel).T4TempateText;
                try
                {
                    (GeneratePageUC.DataContext as GenerateViewPageModel).GeneratedModelView =
                        (GenerateUC.DataContext as GenerateViewModel).GeneratedModelView;
                    (GeneratePageUC.DataContext as GenerateViewPageModel).DoGenerateViewPageModel(Dte, TextTemplating, null,
                                                                                                  (T4EditorPageUC.DataContext as T4EditorViewModel).T4TempatePath);
                    if (aaDialogStarted)
                    {
                        int iOut;
                        aaDialog.EndWaitDialog(out iOut);
                    }
                }
                catch (Exception e)
                {
                    if (aaDialogStarted)
                    {
                        int iOut;
                        aaDialog.EndWaitDialog(out iOut);
                    }
                    MessageBox.Show("Error: " + e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                finally
                {
                    this.CurrentUserControl = GeneratePageUC;
                    this.OnPropertyChanged("CurrentUserControl");
                }
                break;

            case 8:
                CurrentUiStepId = 1;
                NextBtnCommandAction(param);
                break;

            default:
                break;
            }
        }
Ejemplo n.º 31
0
        public async Task <bool> PerformIncludeWhatYouUse(EnvDTE.Document document)
        {
            if (document == null)
            {
                return(false);
            }
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var settingsIwyu = (IncludeWhatYouUseOptionsPage)Package.GetDialogPage(typeof(IncludeWhatYouUseOptionsPage));

            var canCompile = await VSUtils.VCUtils.IsCompilableFile(document);

            if (canCompile.Result == false)
            {
                Output.Instance.WriteLine($"Can't compile file '{canCompile.Reason}': {document.Name}");
                return(false);
            }

            if (WorkInProgress)
            {
                _ = Output.Instance.ErrorMsg("Include What You Use already in progress!");
                return(false);
            }
            WorkInProgress = true;

            // Save all documents.
            try
            {
                document.DTE.Documents.SaveAll();
            }
            catch (Exception saveException)
            {
                Output.Instance.WriteLine("Failed to get save all documents: {0}", saveException);
            }

            var project = document.ProjectItem?.ContainingProject;

            if (project == null)
            {
                Output.Instance.WriteLine("The document {0} is not part of a project.", document.Name);
                return(false);
            }

            var dialogFactory = ServiceProvider.GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;

            if (dialogFactory == null)
            {
                Output.Instance.WriteLine("Failed to get IVsThreadedWaitDialogFactory service.");
                return(false);
            }
            await OptionalDownloadOrUpdate(settingsIwyu, dialogFactory);

            // Start wait dialog.
            {
                IVsThreadedWaitDialog2 dialog = null;
                dialogFactory.CreateInstance(out dialog);
                dialog?.StartWaitDialog("Include Toolbox", "Running include-what-you-use", null, null, "Running include-what-you-use", 0, false, true);

                string output = await IWYU.RunIncludeWhatYouUse(document.FullName, project, settingsIwyu);

                if (settingsIwyu.ApplyProposal && output != null)
                {
                    var settingsFormatting = (FormatterOptionsPage)Package.GetDialogPage(typeof(FormatterOptionsPage));
                    await IWYU.Apply(output, settingsIwyu.RunIncludeFormatter, settingsFormatting);
                }

                dialog?.EndWaitDialog();
            }

            return(true);
        }
Ejemplo n.º 32
0
        static dynamic BuildBTree(ItemIdentifier root)
        {
            Cursor origCursor          = Cursor.Current;
            IVsThreadedWaitDialog2 dlg = null;
            bool     bcanceled;
            int      icanceled, idx = 0;
            DateTime minDate = DateTime.MaxValue, maxDate = DateTime.MinValue;

            Cursor.Current = Cursors.WaitCursor;

            dlg = Utilities.CreateThreadedWaitDialog("Collecting information about changesets", "Starting to process changesets...", "status", 100);
            dlg.UpdateProgress("Collecting information about changesets", "Starting to process changesets...", "status", 0, 100, true, out bcanceled);

            var branches = new List <BTreeItem>();

            foreach (var item in Utilities.vcsrv.QueryRootBranchObjects(RecursionType.Full))
            {
                var itm = new BTreeItem
                {
                    Path            = item.Properties.RootItem.Item,
                    CreationDate    = item.DateCreated,
                    parentPath      = item.Properties.ParentBranch == null ? null : item.Properties.ParentBranch.Item,
                    version         = (item.Properties.RootItem.Version as ChangesetVersionSpec).ChangesetId,
                    RelatedBranches = Utilities.vcsrv
                                      .QueryMergeRelationships(item.Properties.RootItem.Item)
                                      .Select(x => new Tuple <BTreeItem, Changeset[]>(new BTreeItem {
                        Path = x.Item
                    }, Utilities.vcsrv
                                                                                      .GetMergeCandidates(item.Properties.RootItem.Item, x.Item, RecursionType.Full)
                                                                                      .Select(z => z.Changeset).ToArray()))
                                      .ToList()
                };

                if (itm.CreationDate < minDate)
                {
                    minDate = itm.CreationDate;
                }
                if (itm.CreationDate > maxDate)
                {
                    maxDate = itm.CreationDate;
                }
                branches.Add(itm);

                dlg.UpdateProgress("Collecting information about changesets", "Processing branch: " + itm.Path, "status", idx++, 100, false, out bcanceled);
                if (bcanceled)
                {
                    break;
                }
            }

            var broot = new BTreeItem();

            foreach (var itm in branches)
            {
                if (itm.parentPath == null)
                {
                    broot.children.Add(itm);
                    itm.parent = broot;
                }
                else
                {
                    itm.parent = branches.FirstOrDefault(x => x.Path == itm.parentPath);
                    if (itm.parent != null)
                    {
                        itm.parent.children.Add(itm);
                    }
                    else
                    {
                        broot.children.Add(itm);
                    }
                }

                itm.RelatedBranches = itm.RelatedBranches
                                      .Select(x => new Tuple <BTreeItem, Changeset[]>(branches.FirstOrDefault(z => z.Path == x.Item1.Path), x.Item2))
                                      .ToList();

                itm.relY = (int)itm.CreationDate.Subtract(minDate).TotalDays;

                foreach (var ch in itm.RelatedBranches.SelectMany(x => x.Item2))
                {
                    if (ch.CreationDate > maxDate)
                    {
                        maxDate = ch.CreationDate;
                    }
                }
            }

            idx = 0;
            var res = ShowRevHistPackage.TreeDescendants2(broot, ref idx).OrderBy(x => x.relX).ToList();

            res.ForEach(x => Utilities.OutputCommandString(x.relX + " " + (x.parentPath ?? "") + "=" + x.DisplayText));

            Cursor.Current = origCursor;
            dlg.EndWaitDialog(out icanceled);

            return(new {
                ylines = (int)(maxDate.Subtract(minDate).TotalDays * 1.1) + 1,
                xlines = idx + 1,
                branches = res
            });
        }
Ejemplo n.º 33
0
        public static void QueryLinkTypesCallback(object sender, EventArgs e)
        {
            //IntPtr hier;
            //uint itemid;
            //IVsMultiItemSelect dummy;
            //string canonicalName;
            bool   bcanceled;
            int    icanceled;
            string OperationCaption    = "Change Work Items Link Types";
            IVsThreadedWaitDialog2 dlg = null;

            var lkdlg     = new EditLinkTypeDialog(Utilities.wistore);
            var dlgResult = lkdlg.ShowDialog();

            if (dlgResult != DialogResult.OK)
            {
                return;
            }

            var origCursor = Cursor.Current;

            Cursor.Current = Cursors.WaitCursor;

            try
            {
                dlg = Utilities.CreateThreadedWaitDialog(OperationCaption, "Parsing query...", "status", 100);
                dlg.UpdateProgress(OperationCaption, "Parsing query...", "status", 1, 100, true, out bcanceled);

                var WIQueriesPageExt = Utilities.teamExplorer.CurrentPage.GetService <IWorkItemQueriesExt>();
                var qItem            = WIQueriesPageExt.SelectedQueryItems.First();

                int[] qdata;
                int   changedlinks = 0;
                bcanceled = ExecuteQueryLinkTypes(qItem as QueryDefinition, qItem.Project.Name, out qdata);
                dlg.UpdateProgress(OperationCaption, "Changing Link Types...", "status", 1, 100, false, out bcanceled);

                if (!bcanceled)
                {
                    changedlinks = ChangeLinkTypes(qdata, lkdlg.fromlink, lkdlg.tolink);
                }

                dlg.EndWaitDialog(out icanceled);

                if (!bcanceled)
                {
                    MessageBox.Show(changedlinks + " links were changed.", Utilities.AppTitle, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                dlg.EndWaitDialog(out icanceled);
                Cursor.Current = origCursor;
            }
            catch (Exception ex)
            {
                if (dlg != null)
                {
                    dlg.EndWaitDialog(out icanceled);
                }
                Cursor.Current = origCursor;
                Utilities.OutputCommandString(ex.ToString());
                MessageBox.Show(ex.InnerException != null ? ex.InnerException.Message : ex.Message, Utilities.AppTitle, MessageBoxButtons.OK);
            }
        }
        /// <summary>
        /// Tries to create stash staged (if operatiopn wasn't successful - shows Team Explorer notification).
        /// </summary>
        /// <param name="message">message that should be assigned to the Stash.</param>
        /// <returns>True if operation was successful, otherwise - false.</returns>
        public bool TryCreateStashStaged(string message)
        {
            Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();

            IVsThreadedWaitDialog2 dialog = null;

            if (_dialogFactory != null)
            {
                _dialogFactory.CreateInstance(out dialog);
            }

            // Step 1. git stash keep staged.
            if (dialog != null)
            {
                dialog.StartWaitDialogWithPercentageProgress("Stash staged", "Step 1: git stash --keep-index", "Waiting...", null, "Waiting", false, 0, 4, 1);
            }

            if (!_gitCommandExecuter.TryCreateStashKeepIndex(out var errorMessage))
            {
                dialog?.EndWaitDialog(out _);
                _teamExplorer.ShowNotification(errorMessage, NotificationType.Error, NotificationFlags.None, null, Guid.NewGuid());
                return(false);
            }

            // Step 2. git stash
            if (dialog != null)
            {
                dialog.UpdateProgress($"Step 2: git stash save '{message}'", "Waiting...", "Waiting", 2, 4, true, out _);
            }

            if (!_gitCommandExecuter.TryCreateStash(message, true, out errorMessage))
            {
                dialog?.EndWaitDialog(out _);
                _teamExplorer.ShowNotification(errorMessage, NotificationType.Error, NotificationFlags.None, null, Guid.NewGuid());
                return(false);
            }

            // Step 3. git stash apply
            if (dialog != null)
            {
                dialog.UpdateProgress("Step 3: git stash apply stash@{1}", "Waiting...", "Waiting", 3, 4, true, out _);
            }

            if (!_gitCommandExecuter.TryApplyStash(1, out errorMessage))
            {
                dialog?.EndWaitDialog(out _);
                _teamExplorer.ShowNotification(errorMessage, NotificationType.Error, NotificationFlags.None, null, Guid.NewGuid());
                return(false);
            }

            // Step 4. git stash drop
            if (dialog != null)
            {
                dialog.UpdateProgress("Step 4: git stash drop stash@{1}", "Waiting...", "Waiting", 4, 4, true, out _);
            }

            if (!_gitCommandExecuter.TryDeleteStash(1, out errorMessage))
            {
                dialog?.EndWaitDialog(out _);
                _teamExplorer.ShowNotification(errorMessage, NotificationType.Error, NotificationFlags.None, null, Guid.NewGuid());
                return(false);
            }

            dialog?.EndWaitDialog(out _);
            return(true);
        }