private void CreateMessageBasedOnUserSettings(DteWrapper dteWrapper)
        {
            var storedSettings        = mediatrSettingsStoreManager.GetAllSettingsByProject(dteWrapper.SelectedProject);
            var messageSettingsWindow = new MediatrMessageSettingsWindow(storedSettings);
            var windowResult          = WindowHelper.ShowModal(messageSettingsWindow);

            if (WindowResultSucceeded(windowResult))
            {
                waitDialog.StartWaitDialog(
                    "Creating MeditR message...",
                    "Please wait...",
                    null,
                    0,
                    "MeditR message creating...",
                    0,
                    false,
                    true
                    );

                var mediatRMessageCreateModel = messageSettingsWindow.GetCreateMessageModel();
                CreateMediatrMessage(dteWrapper, mediatRMessageCreateModel);
                mediatrSettingsStoreManager.SaveUserSettigs(dteWrapper.SelectedProject, mediatRMessageCreateModel);

                waitDialog.EndWaitDialog();
            }
        }
        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;
            }
        }
Пример #3
0
 public void Dispose()
 {
     if (ErrorHandler.Succeeded(_waitResult))
     {
         int cancelled = 0;
         _waitDialog.EndWaitDialog(out cancelled);
     }
 }
Пример #4
0
        public override void DoCommand(object sender, EventArgs args)
        {
            var webSite = GetSelectedAzureWebSite();

            if (webSite == null)
            {
                throw new NotSupportedException();
            }

            Uri debugUri;

            if (Uri.TryCreate(webSite.Uri, "/ptvsd", out debugUri))
            {
                // Open the site's ptvsd page if it exists
                var req = WebRequest.CreateHttp(debugUri.AbsoluteUri);
                req.Method = "HEAD";
                req.Accept = "text/html";

                var dlgFactory             = (IVsThreadedWaitDialogFactory)_serviceProvider.GetService(typeof(SVsThreadedWaitDialogFactory));
                IVsThreadedWaitDialog2 dlg = null;
                if (dlgFactory != null && ErrorHandler.Succeeded(dlgFactory.CreateInstance(out dlg)))
                {
                    if (ErrorHandler.Failed(dlg.StartWaitDialog(
                                                Strings.ProductTitle,
                                                Strings.DebugAttachGettingSiteInformation,
                                                null,
                                                null,
                                                null,
                                                1,
                                                false,
                                                true
                                                )))
                    {
                        dlg = null;
                    }
                }
                try {
                    req.GetResponse().Close();
                } catch (WebException) {
                    debugUri = null;
                } finally {
                    if (dlg != null)
                    {
                        int dummy;
                        dlg.EndWaitDialog(out dummy);
                    }
                }
            }

            if (debugUri != null)
            {
                CommonPackage.OpenWebBrowser(_serviceProvider, debugUri.AbsoluteUri);
            }
            else
            {
                CommonPackage.OpenWebBrowser(_serviceProvider, "http://go.microsoft.com/fwlink/?LinkID=624026");
            }
        }
Пример #5
0
        public async Task <bool> PerformTrialAndErrorIncludeRemoval(EnvDTE.Document document, TrialAndErrorRemovalOptionsPage settings)
        {
            if (document == null)
            {
                return(false);
            }

            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            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("Trial and error include removal already in progress!");
                return(false);
            }
            WorkInProgress = true;

            // Start wait dialog.
            IVsThreadedWaitDialog2 progressDialog = await StartProgressDialog(document.Name);

            if (progressDialog == null)
            {
                return(false);
            }

            // Extract all includes.
            ITextBuffer textBuffer;

            Formatter.IncludeLineInfo[] includeLines;
            try
            {
                ExtractSelectionAndIncludes(document, settings, out textBuffer, out includeLines);
            }
            catch (Exception ex)
            {
                Output.Instance.WriteLine("Unexpected error while extracting include selection: {0}", ex);
                progressDialog.EndWaitDialog();
                return(false);
            }

            // Hook into build events.
            SubscribeBuildEvents();

            // The rest runs in a separate thread since the compile function is non blocking and we want to use BuildEvents
            // We are not using Task, since we want to make use of WaitHandles - using this together with Task is a bit more complicated to get right.
            outputWaitEvent.Reset();
            var removalThread = new System.Threading.Thread(() => TrialAndErrorRemovalThreadFunc(document, settings, includeLines, progressDialog, textBuffer));

            removalThread.Start();
            return(true);
        }
Пример #6
0
            public void Dispose()
            {
                int canceled;

                if (_dlg2 != null)
                {
                    _dlg2.EndWaitDialog(out canceled);
                }
            }
Пример #7
0
        private void CloseProgressDialog(IVsThreadedWaitDialog2 vsThreadedWaitDialog)
        {
            if (vsThreadedWaitDialog == null)
            {
                throw new ArgumentNullException("vsThreadedWaitDialog");
            }

            int canceled;

            ErrorHandler.ThrowOnFailure(vsThreadedWaitDialog.EndWaitDialog(out canceled));
        }
Пример #8
0
        private void LoadGraphFromTemp()
        {
            var result = MessageBox.Show("New SEViz graph is available. Do you want to load it?", "SEViz notification", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.Yes)
            {
                var dialogFactory = ViewerWindowCommand.Instance.ServiceProvider.GetService(typeof(SVsThreadedWaitDialogFactory)) as IVsThreadedWaitDialogFactory;

                IVsThreadedWaitDialog2 dialog = null;
                if (dialogFactory != null)
                {
                    dialogFactory.CreateInstance(out dialog);
                }
                if (dialog != null)
                {
                    bw = new BackgroundWorker();
                    bw.WorkerSupportsCancellation = true;
                    bw.DoWork += (p1, p2) =>
                    {
                        dialog.StartWaitDialog("SEViz", "SEViz is loading", "Please wait while SEViz loads the graph...", null, "Waiting status bar text", 0, false, true);
                        while (true)
                        {
                            if (!bw.CancellationPending)
                            {
                                Thread.Sleep(500);
                            }
                            else
                            {
                                break;
                            }
                        }
                    };
                    bw.RunWorkerCompleted += (p1, p2) =>
                    {
                        int isCanceled = -1;
                        dialog.EndWaitDialog(out isCanceled);
                    };
                    bw.RunWorkerAsync();

                    // Loading the graph
                    LoadGraph(SEGraph.Deserialize(Path.GetTempPath() + "SEViz/" + "temp.graphml"));

                    // Setting the caption of the tool window
                    ViewerWindowCommand.Instance.FindToolWindow().Caption = Graph.Vertices.Where(v => !v.SourceCodeMappingString.Equals("")).FirstOrDefault().MethodName + " - SEViz";

                    // Showing the tool window
                    ViewerWindowCommand.Instance.ShowToolWindow(null, null);
                }
            }

            fsw.EnableRaisingEvents = true;
        }
Пример #9
0
 private void CloseDialog()
 {
     try
     {
         uiThreadDispatcher.Invoke(() =>
         {
             waitDialog?.EndWaitDialog();
         });
     }
     catch
     {
     }
 }
Пример #10
0
        internal bool End()
        {
            var hasCanceled = 0;

            Debug.Assert(_dialogStarted, "attempting to end a non-running dialog");
            if (_dialogStarted)
            {
                ThrowOnFailure(_waitDialog.EndWaitDialog(out hasCanceled));
                _dialogStarted = false;
            }

            return(Convert.ToBoolean(hasCanceled));
        }
Пример #11
0
        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
                    int canceled;
                    dialog?.EndWaitDialog(out canceled);
                }
            }
        }
Пример #12
0
        private void RunPostDownloadWork(object sender, AsyncCompletedEventArgs e)
        {
            webClient.Dispose();
            waitDialog?.EndWaitDialog();

            if (!IsCanceledByUser)
            {
                OnDownloadCompleted?.Invoke(dest);
            }
            else
            {
                DeleteFileSync();
                OnDownloadCanceled?.Invoke(dest);
            }
        }
Пример #13
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);
        }
Пример #14
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));
            }
        }
Пример #15
0
 public void EndWaitDialog()
 {
     if (_waitDialog == null)
     {
         return;
     }
     lock (_waitDialog)
     {
         int canceled;
         if (!_started)
         {
             return;
         }
         int hr = _waitDialog.EndWaitDialog(out canceled);
         if (hr != VSConstants.S_OK)
         {
             return;
         }
         _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);
        }
        public static async Task <Report> ProcessAsync(IAsyncServiceProvider serviceProvider, bool addComment)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            var report = new Report();

            var dte = (DTE)await serviceProvider.GetServiceAsync(typeof(DTE));

            if (dte == null || string.IsNullOrEmpty(dte.Solution.FullName))
            {
                report.SolutionName = "N/A";
                return(report);
            }

            report.SolutionName = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetFileName(dte.Solution.FullName));

            IVsStatusbar statusBar = (IVsStatusbar)await serviceProvider.GetServiceAsync(typeof(SVsStatusbar));

            IVsThreadedWaitDialogFactory factory =
                (IVsThreadedWaitDialogFactory)await serviceProvider.GetServiceAsync(
                    typeof(SVsThreadedWaitDialogFactory));

            IVsThreadedWaitDialog2 dialog = null;

            factory?.CreateInstance(out dialog);
            dialog?.StartWaitDialog("PVSStudio Helper", (addComment) ? "Add comment" : "Remove comment", null, null,
                                    null, 0, false, true);

            IVsOutputWindow outWindow =
                (IVsOutputWindow)await serviceProvider.GetServiceAsync(typeof(SVsOutputWindow));

            var generalPaneGuid             = VSConstants.GUID_OutWindowGeneralPane; // P.S. There's also the GUID_OutWindowDebugPane available.
            IVsOutputWindowPane generalPane = null;

            outWindow?.GetPane(ref generalPaneGuid, out generalPane);
            if (generalPane == null)
            {
                outWindow?.CreatePane(ref generalPaneGuid, "General", 1, 0);
                outWindow?.GetPane(ref generalPaneGuid, out generalPane);
            }

            await ProjectProcess.ProcessAsync(dte, report, addComment, async (message) =>
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
                dialog?.UpdateProgress(null, message, null, 0, 0, true, out var canceled);
                //messagePump.WaitText = message;
                if (statusBar != null)
                {
                    statusBar.IsFrozen(out var isFrozen);
                    if (isFrozen == 0)
                    {
                        statusBar.SetText(message);
                    }
                }

                generalPane?.OutputString($"{message}{Environment.NewLine}");
            });

            var finalMessage =
                $"The solution {report.SolutionName} processed. Processed items: {report.ProcessedItems}, include opened items {report.ProcessedOpenedItems}";

            if (statusBar != null)
            {
                statusBar.IsFrozen(out var isFrozen);
                if (isFrozen == 0)
                {
                    statusBar.SetText(finalMessage);
                }
            }
            generalPane?.OutputStringThreadSafe($"{finalMessage}{Environment.NewLine}");

            dialog.EndWaitDialog();

            return(report);
        }
Пример #18
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);
        }
Пример #19
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();
            }
        }
Пример #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;
            }
        }
Пример #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();
            }
        }
Пример #22
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);
            }
        }
Пример #23
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;
            }
        }
Пример #24
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);
            }
        }
Пример #25
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);
            }
        }
Пример #26
0
        private async System.Threading.Tasks.Task RestorePackagesOrCheckForMissingPackages(vsBuildScope scope)
        {
            _msBuildOutputVerbosity = GetMSBuildOutputVerbositySetting(_dte);
            var waitDialogFactory = ServiceLocator.GetGlobalService <SVsThreadedWaitDialogFactory, IVsThreadedWaitDialogFactory>();

            waitDialogFactory.CreateInstance(out _waitDialog);
            var token = CancellationTokenSource.Token;

            try
            {
                if (IsConsentGranted())
                {
                    if (scope == vsBuildScope.vsBuildScopeSolution || scope == vsBuildScope.vsBuildScopeBatch || scope == vsBuildScope.vsBuildScopeProject)
                    {
                        TotalCount = (await PackageRestoreManager.GetMissingPackagesInSolution(token)).ToList().Count;
                        if (TotalCount > 0)
                        {
                            if (_outputOptOutMessage)
                            {
                                _waitDialog.StartWaitDialog(
                                    Resources.DialogTitle,
                                    Resources.RestoringPackages,
                                    String.Empty,
                                    varStatusBmpAnim: null,
                                    szStatusBarText: null,
                                    iDelayToShowDialog: 0,
                                    fIsCancelable: true,
                                    fShowMarqueeProgress: true);
                                WriteLine(VerbosityLevel.Quiet, Resources.PackageRestoreOptOutMessage);
                                _outputOptOutMessage = false;
                            }

                            System.Threading.Tasks.Task waitDialogCanceledCheckTask = System.Threading.Tasks.Task.Run(() =>
                            {
                                // Just create an extra task that can keep checking if the wait dialog was cancelled
                                // If so, cancel the CancellationTokenSource
                                bool canceled = false;
                                try
                                {
                                    while (!canceled && CancellationTokenSource != null && !CancellationTokenSource.IsCancellationRequested && _waitDialog != null)
                                    {
                                        _waitDialog.HasCanceled(out canceled);
                                        // Wait on the cancellation handle for 100ms to avoid checking on the wait dialog too frequently
                                        CancellationTokenSource.Token.WaitHandle.WaitOne(100);
                                    }

                                    CancellationTokenSource.Cancel();
                                }
                                catch (Exception)
                                {
                                    // Catch all and don't throw
                                    // There is a slight possibility that the _waitDialog was set to null by another thread right after the check for null
                                    // So, it could be null or disposed. Just ignore all errors
                                }
                            });

                            System.Threading.Tasks.Task whenAllTaskForRestorePackageTasks =
                                System.Threading.Tasks.Task.WhenAll(SolutionManager.GetNuGetProjects().Select(nuGetProject => RestorePackagesInProject(nuGetProject, token)));

                            await System.Threading.Tasks.Task.WhenAny(whenAllTaskForRestorePackageTasks, waitDialogCanceledCheckTask);

                            // Once all the tasks are completed, just cancel the CancellationTokenSource
                            // This will prevent the wait dialog from getting updated
                            CancellationTokenSource.Cancel();
                        }
                    }
                    else
                    {
                        throw new NotImplementedException();
                    }
                }
                else
                {
                    _waitDialog.StartWaitDialog(
                        Resources.DialogTitle,
                        Resources.RestoringPackages,
                        String.Empty,
                        varStatusBmpAnim: null,
                        szStatusBarText: null,
                        iDelayToShowDialog: 0,
                        fIsCancelable: true,
                        fShowMarqueeProgress: true);
                    CheckForMissingPackages((await PackageRestoreManager.GetMissingPackagesInSolution(token)).ToList());
                }
            }
            finally
            {
                int canceled;
                _waitDialog.EndWaitDialog(out canceled);
                _waitDialog = null;
            }

            await PackageRestoreManager.RaisePackagesMissingEventForSolution(CancellationToken.None);
        }
        /// <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);
        }
Пример #28
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
            });
        }
Пример #29
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;
            }
        }
Пример #30
0
        public void Dispose()
        {
            int cancelled;

            waitDialog.EndWaitDialog(out cancelled);
        }