示例#1
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress);

            var container = new DependencyContainer();

            var commandService = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;

            container.RegisterInstance(typeof(IMenuCommandService), commandService);


            var dte = await GetServiceAsync(typeof(SDTE)) as DTE2;

            var visualStudioService = new VisualStudioService(dte);

            container.RegisterInstance(typeof(IVisualStudioService), visualStudioService);

            //there is code in the module loading which adds buttons to the vs runtime
            //by calling a method which is apparently not allowed to be called in asynch await threads
            //this line of code before it appears to switch to the main thread which avoids the problem
            //as per these links
            //https://github.com/madskristensen/CustomCommandSample
            //https://social.msdn.microsoft.com/Forums/vstudio/en-US/dc8ba70b-0faf-4a16-96a4-1c57dac3e7a7/cant-get-olemenucommandservice-asynchronously-when-implementing-iasyncloadablepackageinitialize?forum=vsx
            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            var app = Factory.CreateJosephMXrmVsixApp(visualStudioService, container);
        }
 protected override void LoadDialogExtention()
 {
     //if we do not yet have connections added to the package settings
     //then lets add the active connection to the settings as the active connection
     if (SettingsObject.Connections == null ||
         !SettingsObject.Connections.Any())
     {
         try
         {
             var savedConnection = SavedXrmRecordConfiguration.CreateNew(XrmRecordService.XrmRecordConfiguration);
             savedConnection.Active     = true;
             SettingsObject.Connections = new[] { savedConnection };
         }
         catch (Exception)
         {
             //No matter if this happens user may just add it in anyway
         }
     }
     if (VisualStudioService != null && string.IsNullOrWhiteSpace(SettingsObject.SolutionObjectPrefix))
     {
         var solutionName = VisualStudioService.GetSolutionName();
         if (!string.IsNullOrWhiteSpace(solutionName))
         {
             SettingsObject.SolutionObjectPrefix = solutionName.Split('.').First();
         }
     }
     StartNextAction();
 }
        public void VsixDeployWebResourcesTest()
        {
            //first delete all the test deployed javascriot files
            var javaScriptFiles = GetJavaScriptFiles();

            DeleteJavaScriptFileRecords();
            Assert.IsFalse(GetJavaScriptFileRecords().Any());

            //create an app, deploy and verify created
            VisualStudioService.SetSelectedItems(GetJavaScriptFiles().Select(f => new FakeVisualStudioProjectItem(f)).ToArray());
            var app = CreateAndLoadTestApplication <DeployWebResourceModule>();

            //run the deploy including a redirect to enter package settings first
            var originalConnection = HijackForPackageEntryRedirect(app);
            //lets delete the settings files, then verify they are recreated during the redirect entry
            var solutionItemsFolder = Path.Combine(VisualStudioService.SolutionDirectory, VisualStudioService.ItemFolderName);

            FileUtility.DeleteFiles(solutionItemsFolder);
            var solutionSettingFiles = FileUtility.GetFiles(solutionItemsFolder);

            Assert.AreEqual(0, solutionSettingFiles.Count());

            //run the dialog
            var dialog = app.NavigateToDialog <DeployWebResourceModule, DeployWebResourceDialog>();

            VerifyPackageEntryRedirect(originalConnection, dialog);
            //verify the 2 settings files recreated
            solutionSettingFiles = FileUtility.GetFiles(solutionItemsFolder);
            Assert.AreEqual(2, solutionSettingFiles.Count());
            Assert.AreEqual(GetJavaScriptFiles().Count(), GetJavaScriptFileRecords().Count());

            var records             = GetJavaScriptFileRecords();
            var currentComponentIds = XrmRecordService.GetSolutionComponents(dialog.Service.PackageSettings.Solution.Id, OptionSets.SolutionComponent.ObjectTypeCode.WebResource).ToList();

            Assert.IsTrue(records.All(r => currentComponentIds.Contains(r.Id)));
            //okay the code also allows match by display name
            //so I will add this to verify that too
            //basically change ones display name and file name then verify it still matches
            var files         = GetJavaScriptFiles();
            var firstFileInfo = new FileInfo(files.First());
            var record        = records.First(e => e.GetStringField(Fields.webresource_.name) == firstFileInfo.Name);

            XrmRecordService.Delete(record);
            var newRecord = XrmRecordService.NewRecord(Entities.webresource);

            newRecord.SetField(Fields.webresource_.name, "jrm_fakescriptname", XrmRecordService);
            newRecord.SetField(Fields.webresource_.displayname, firstFileInfo.Name, XrmRecordService);
            newRecord.SetField(Fields.webresource_.webresourcetype, OptionSets.WebResource.Type.ScriptJScript, XrmRecordService);
            XrmRecordService.Create(newRecord);

            //create an app, deploy again and verify not duplicated
            VisualStudioService.SetSelectedItems(GetJavaScriptFiles().Select(f => new FakeVisualStudioProjectItem(f)).ToArray());
            app    = CreateAndLoadTestApplication <DeployWebResourceModule>();
            dialog = app.NavigateToDialog <DeployWebResourceModule, DeployWebResourceDialog>();

            Assert.AreEqual(GetJavaScriptFiles().Count(), GetJavaScriptFileRecords().Count());
        }
示例#4
0
            public async Task <Process> Launch(SessionViewModel session)
            {
                if (process == null)
                {
                    process = await VisualStudioService.StartVisualStudio(session, ideInfo);

                    process?.WaitForInputIdle();
                }

                return(process);
            }
示例#5
0
 protected override void CompleteDialogExtention()
 {
     if (AddToSolution)
     {
         VisualStudioService.AddSolutionItem("solution.xrmconnection", ObjectToEnter);
     }
     CompletionMessage = "Connection Refreshed";
     if (DoPostEntry != null)
     {
         DoPostEntry();
     }
 }
示例#6
0
 protected override void LoadDialogExtention()
 {
     AssemblyName = VisualStudioService.GetSelectedProjectAssemblyName();
     if (string.IsNullOrWhiteSpace(AssemblyName))
     {
         throw new NullReferenceException("Could Not Find Assembly Name");
     }
     else
     {
         StartNextAction();
     }
 }
        public override void RunStartedExtention(Dictionary <string, string> replacementsDictionary)
        {
            //get a xrm connection and package setting by loading the entry dialogs
            XrmPackageSettings = new XrmPackageSettings();
            if (replacementsDictionary.ContainsKey("$projectname$"))
            {
                XrmPackageSettings.PluginProjects = new[]
                {
                    new XrmPackageSettings.PluginProject(replacementsDictionary["$projectname$"] + ".Plugins")
                };
                XrmPackageSettings.WebResourceProjects = new[]
                {
                    new XrmPackageSettings.WebResourceProject(replacementsDictionary["$projectname$"] + ".WebResources")
                };
            }
            var visualStudioService = new VisualStudioService(DTE);
            var container           = new DependencyContainer();

            container.RegisterInstance <IVisualStudioService>(visualStudioService);
            var app = Factory.CreateJosephMXrmVsixApp(visualStudioService, container, isWizardContext: true);

            VsixApplication = app;
            app.VsixApplicationController.LogEvent("Xrm Solution Template Wizard Loaded");
            try
            {
                if (replacementsDictionary.ContainsKey("$specifiedsolutionname$") && (replacementsDictionary["$specifiedsolutionname$"] == null || replacementsDictionary["$specifiedsolutionname$"] == ""))
                {
                    app.Controller.UserMessage("Warning! When Creating The Solution If 'Create Directory For Solution' Is Not Set In Visual Studio 2017, Or If 'Place Solution And Project In The Same Directory' Is Set In Visual Studio 2019, Then The New Solution May Not Be Created Correctly Due To Visual Studio Placing The .sln File In An Incorrect Folder Or Creating A Nested Projects Folder. Recommend Restarting The Solution Creation With This Checked Appropriately");
                }

                var solutionName = replacementsDictionary.ContainsKey("$specifiedsolutionname$") &&
                                   replacementsDictionary["$specifiedsolutionname$"] != null
                    ? replacementsDictionary["$specifiedsolutionname$"]
                    : null;

                RunWizardSettingsEntry(XrmPackageSettings, app.VsixApplicationController, solutionName);

                //add token replacements for the template projects
                AddReplacements(replacementsDictionary, XrmPackageSettings);

                //used later
                DestinationDirectory = replacementsDictionary["$destinationdirectory$"];
                SafeProjectName      = replacementsDictionary["$safeprojectname$"];
            }
            catch (Exception ex)
            {
                app.VsixApplicationController.LogEvent("Xrm Solution Template Wizard Fatal Error", new Dictionary <string, string> {
                    { "Is Error", true.ToString() }, { "Error", ex.Message }, { "Error Trace", ex.DisplayString() }
                });
                throw;
            }
        }
        protected override void ProcessCompletionExtention()
        {
            base.ProcessCompletionExtention();

            LogController.UpdateProgress(7, 8, "Moving Package Into Solution Folder");

            var folder = Request.FolderPath.FolderPath;

            //!! NOTE THE Releases Folder name is repeated in the DeployPackageCommand visibility criteria + test scripts !!
            var solutionFolder = Path.Combine(VisualStudioService.SolutionDirectory, "Releases", Request.ThisReleaseVersion);

            FileUtility.MoveWithReplace(folder, solutionFolder);

            LogController.UpdateProgress(3, 3, "Adding Package To Solution");

            VisualStudioService.AddFolder(solutionFolder);
        }
示例#9
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            var container = new DependencyContainer();

            var commandService = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            container.RegisterInstance(typeof(IMenuCommandService), commandService);


            var dte = GetService(typeof(SDTE)) as DTE2;
            var visualStudioService = new VisualStudioService(dte);

            container.RegisterInstance(typeof(IVisualStudioService), visualStudioService);

            var app = Factory.CreateJosephMXrmVsixApp(visualStudioService, container);
        }
        protected override void CompleteDialogExtention()
        {
            if (SaveSettings)
            {
                base.CompleteDialogExtention();
                //set the active connection to the connection selected as active
                if (SettingsObject.Connections != null)
                {
                    var activeConnections = SettingsObject.Connections.Where(c => c.Active);
                    if (activeConnections.Any())
                    {
                        var activeConnection = activeConnections.First();
                        VisualStudioService.AddSolutionItem("solution.xrmconnection", activeConnection);
                    }
                }
            }

            CompletionMessage = "Settings Updated";
        }
        protected override void CompleteDialogExtention()
        {
            if (SaveSettings)
            {
                base.CompleteDialogExtention();
                //set the active connection to the connection selected as active
                if (SettingsObject.Connections != null)
                {
                    var activeConnections = SettingsObject.Connections.Where(c => c.Active);
                    if (activeConnections.Any())
                    {
                        var activeConnection = activeConnections.First();
                        VisualStudioService.AddSolutionItem("solution.xrmconnection", activeConnection);

                        XrmConnectionModule.RefreshXrmServices(activeConnection, ApplicationController, xrmRecordService: (RefreshActiveServiceConnection ? XrmRecordService : null));
                    }
                }
            }
            CompletionMessage = "Settings Updated";
        }
示例#12
0
        private static async Task <Process> GetDebuggerProcess(EditorViewModel editor)
        {
            // Check if the current solution is opened in some IDE instance
            var process = await VisualStudioService.GetVisualStudio(editor.Session, false);

            if (process == null)
            {
                // If not, let the user pick an instance
                var picker = new DebuggerPickerWindow(VisualStudioDTE.GetActiveInstances());

                var result = await picker.ShowModal();

                if (result == DialogResult.Ok)
                {
                    process = await picker.SelectedDebugger.Launch(editor.Session);
                }
            }

            return(process);
        }
示例#13
0
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            var container = new DependencyContainer();

            var commandService = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            container.RegisterInstance(typeof(IMenuCommandService), commandService);


            var dte = GetService(typeof(SDTE)) as DTE2;
            var visualStudioService = new VisualStudioService(dte);

            container.RegisterInstance(typeof(IVisualStudioService), visualStudioService);

            var applicationController = new VsixApplicationController(container);
            var app = new VsixApplication(applicationController, new VsixSettingsManager(visualStudioService), new Guid("43816e6d-4db8-48d6-8bfa-75916cb080f0"));

            app.AddModule <OpenWebModule>(0x010B);
            app.AddModule <OpenSolutionModule>(0x010C);
            app.AddModule <OpenAdvancedFindModule>(0x010D);
            app.AddModule <ClearCacheModule>(0x0109);
            app.AddModule <XrmCrudModule>(0x0112);
            app.AddModule <InstanceComparerModule>(0x0111);
            app.AddModule <UpdateAssemblyModule>(0x0105);
            app.AddModule <XrmPackageSettingsModule>(0x0106);
            app.AddModule <DeployAssemblyModule>(0x0103);
            app.AddModule <ManagePluginTriggersModule>(0x0104);
            app.AddModule <VsixCustomisationImportModule>(0x010A);
            app.AddModule <VsixCreatePackageModule>(0x010E);
            app.AddModule <RefreshSchemaModule>(0x0100);
            app.AddModule <DeployWebResourceModule>(0x0102);
            app.AddModule <VsixImportCsvsModule>(0x0108);
            app.AddModule <VsixDeployPackageModule>(0x0110);
            app.AddModule <XrmTextSearchModule>(0x0116);
            app.AddModule <XrmPackageAboutModule>(0x0113);
            app.AddModule <ImportSolutionModule>(0x0114);
            app.AddModule <ImportRecordsModule>(0x0115);
            app.AddModule <DeployIntoFieldModule>(0x0117);
        }
示例#14
0
        public void VsixDeployWebResourcesTest()
        {
            //first delete all the test deployed javascriot files
            var javaScriptFiles = GetJavaScriptFiles();

            DeleteJavaScriptFileRecords();
            Assert.IsFalse(GetJavaScriptFileRecords().Any());

            //create an app, deploy and verify created
            VisualStudioService.SetSelectedItems(GetJavaScriptFiles().Select(f => new FakeVisualStudioProjectItem(f)).ToArray());
            var testApplication = CreateAndLoadTestApplication <DeployWebResourceModule>();
            var dialog          = testApplication.NavigateToDialog <DeployWebResourceModule, DeployWebResourceDialog>();

            Assert.AreEqual(GetJavaScriptFiles().Count(), GetJavaScriptFileRecords().Count());

            //create an app, deploy againb and verify not duplicated
            VisualStudioService.SetSelectedItems(GetJavaScriptFiles().Select(f => new FakeVisualStudioProjectItem(f)).ToArray());
            testApplication = CreateAndLoadTestApplication <DeployWebResourceModule>();
            dialog          = testApplication.NavigateToDialog <DeployWebResourceModule, DeployWebResourceDialog>();

            Assert.AreEqual(GetJavaScriptFiles().Count(), GetJavaScriptFileRecords().Count());
        }
示例#15
0
        public void VsixDeployAssemblyDialogWhereBuildFailedTest()
        {
            var testApplication = CreateAndLoadTestApplication <DeployAssemblyModule>(loadXrmConnection: false);

            //this fakes a failed build as there is no assembly returned when build and get assembly called
            VisualStudioService.SetSelectedProjectAssembly(null);

            //navigate to deploy assembly
            var module = testApplication.GetModule <DeployAssemblyModule>();

            module.DialogCommand();
            var dialog = testApplication.GetNavigatedDialog <DeployAssemblyDialog>();

            //verify straight to completion screen
            var completionScreen = dialog.Controller.UiItems.First() as CompletionScreenViewModel;

            Assert.IsNotNull(completionScreen);
            Assert.IsNotNull(completionScreen.CompletionDetails);
            completionScreen.CompletionDetails.LoadFormSections();

            Assert.IsNotNull(completionScreen.CompletionDetails.GetStringFieldFieldViewModel(nameof(DeployAssemblyResponse.Message)).Value);
        }
        protected override void CompleteDialogExtention()
        {
            if (SaveSettings)
            {
                var isMovingFolder = VisualStudioService.GetSolutionFolder(VisualStudioService.ItemFolderName) == null &&
                                     VisualStudioService.GetItemText("solution.xrmconnection", "SolutionItems") != null;
                base.CompleteDialogExtention();
                //set the active connection to the connection selected as active
                if (SettingsObject.Connections != null)
                {
                    var activeConnections = SettingsObject.Connections.Where(c => c.Active);
                    if (activeConnections.Any())
                    {
                        var activeConnection = activeConnections.First();
                        var settingsManager  = ApplicationController.ResolveType(typeof(ISettingsManager)) as ISettingsManager;
                        if (settingsManager == null)
                        {
                            throw new NullReferenceException("settingsManager");
                        }
                        settingsManager.SaveSettingsObject(activeConnection);

                        XrmConnectionModule.RefreshXrmServices(activeConnection, ApplicationController, xrmRecordService: (RefreshActiveServiceConnection ? XrmRecordService : null));
                        LookupService = (XrmRecordService)ApplicationController.ResolveType(typeof(XrmRecordService));
                    }
                }
                if (isMovingFolder)
                {
                    var openIt = ApplicationController.UserConfirmation("This Visual Studio extention is changing the way saved settings are stored. Click yes to open a window outlining the changes, and detailing code changes required if you use instances of the Xrm Solution Template");
                    if (openIt)
                    {
                        var blah             = new SettingsFolderMoving();
                        var displaySomething = new ObjectDisplayViewModel(blah, FormController.CreateForObject(blah, ApplicationController, null));
                        ApplicationController.NavigateTo(displaySomething);
                    }
                }
            }
            CompletionMessage = "Settings Updated";
        }
        public void VsixDeployWebResourcesTest()
        {
            //first delete all the test deployed javascriot files
            var javaScriptFiles = GetJavaScriptFiles();

            DeleteJavaScriptFileRecords();
            Assert.IsFalse(GetJavaScriptFileRecords().Any());

            //create an app, deploy and verify created
            VisualStudioService.SetSelectedItems(GetJavaScriptFiles().Select(f => new FakeVisualStudioProjectItem(f)).ToArray());
            var testApplication = CreateAndLoadTestApplication <DeployWebResourceModule>();
            var dialog          = testApplication.NavigateToDialog <DeployWebResourceModule, DeployWebResourceDialog>();

            Assert.AreEqual(GetJavaScriptFiles().Count(), GetJavaScriptFileRecords().Count());

            //okay the code also allows match by display name
            //so I will add this to verify that too
            //basically change ones display name and file name then verify it still matches
            var files         = GetJavaScriptFiles();
            var records       = GetJavaScriptFileRecords();
            var firstFileInfo = new FileInfo(files.First());
            var record        = records.First(e => e.GetStringField(Fields.webresource_.name) == firstFileInfo.Name);

            XrmRecordService.Delete(record);
            var newRecord = XrmRecordService.NewRecord(Entities.webresource);

            newRecord.SetField(Fields.webresource_.name, "jrm_fakescriptname", XrmRecordService);
            newRecord.SetField(Fields.webresource_.displayname, firstFileInfo.Name, XrmRecordService);
            newRecord.SetField(Fields.webresource_.webresourcetype, OptionSets.WebResource.Type.ScriptJScript, XrmRecordService);
            XrmRecordService.Create(newRecord);

            //create an app, deploy again and verify not duplicated
            VisualStudioService.SetSelectedItems(GetJavaScriptFiles().Select(f => new FakeVisualStudioProjectItem(f)).ToArray());
            testApplication = CreateAndLoadTestApplication <DeployWebResourceModule>();
            dialog          = testApplication.NavigateToDialog <DeployWebResourceModule, DeployWebResourceDialog>();

            Assert.AreEqual(GetJavaScriptFiles().Count(), GetJavaScriptFileRecords().Count());
        }
        private string LoadAssemblyDetails()
        {
            AssemblyFile = VisualStudioService.BuildSelectedProjectAndGetAssemblyName();
            if (string.IsNullOrWhiteSpace(AssemblyFile))
            {
                return("Could Not Find Built Assembly. Check The Build Result For Errors");
            }


            var fileInfo     = new FileInfo(AssemblyFile);
            var assemblyName = fileInfo.Name.Substring(0,
                                                       fileInfo.Name.LastIndexOf(fileInfo.Extension, StringComparison.Ordinal));

            var bytes           = File.ReadAllBytes(AssemblyFile);
            var assemblyContent = Convert.ToBase64String(bytes);

            //okay this crazy stuff is to load the assembly dll in a different app domain
            //that way it may be loaded, inspected, then released (removing any lock on the assembly file)
            //when the appdomain is unloaded
            //the loading and inspection is done in an object PluginAssemblyReader
            //which is loaded in the context of the separate app domain
            var myDomain = AppDomain.CreateDomain("JosephM.XRM.VSIX.DeployAssemblyCommand", null, null);

            AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
            IEnumerable <PluginAssemblyReader.PluginType> plugins;
            bool isSigned = false;

            try
            {
                var reader =
                    (PluginAssemblyReader)
                    myDomain.CreateInstanceFrom(
                        Assembly.GetExecutingAssembly().Location,
                        typeof(PluginAssemblyReader).FullName).Unwrap();
                var loadResponse = reader.LoadTypes(AssemblyFile);
                isSigned = loadResponse.IsSigned;
                var loadedPlugins = loadResponse.PluginTypes;
                plugins =
                    loadedPlugins.Select(p => new PluginAssemblyReader.PluginType(p.Type, p.TypeName)).ToArray();
            }
            finally
            {
                AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
                if (null != myDomain)
                {
                    AppDomain.Unload(myDomain);
                }
            }
            if (!isSigned)
            {
                return("Assembly Cannot By Deployed. You Need To Sign The Assembly With A Strong Named Key File");
            }
            if (!plugins.Any())
            {
                return("Assembly Cannot By Deployed. No Plugin Classes Were Found In The Assembly");
            }

            Request.AssemblyName = assemblyName;
            Request.Content      = assemblyContent;

            var preAssembly = XrmRecordService.GetFirst(Entities.pluginassembly, Fields.pluginassembly_.name, assemblyName);

            if (preAssembly != null)
            {
                Request.Id            = preAssembly.Id;
                Request.IsolationMode = preAssembly.GetOptionKey(Fields.pluginassembly_.isolationmode).ParseEnum <DeployAssemblyRequest.IsolationMode_>();
            }

            var pluginTypes = new List <PluginType>();

            Request.PluginTypes = pluginTypes;
            foreach (var item in plugins)
            {
                var pluginType = new PluginType();
                pluginType.TypeName = item.TypeName;
                //get the type name after "." as the name
                var startIndex = item.TypeName.LastIndexOf(".", StringComparison.Ordinal);
                if (startIndex != -1 && item.TypeName.Length > startIndex + 1)
                {
                    startIndex = startIndex + 1;
                }
                else
                {
                    startIndex = 0;
                }
                pluginType.FriendlyName       = item.TypeName.Substring(startIndex);
                pluginType.Name               = item.TypeName.Substring(startIndex);
                pluginType.IsWorkflowActivity = item.Type == PluginAssemblyReader.PluginType.XrmPluginType.WorkflowActivity;
                pluginType.InAssembly         = true;
                pluginTypes.Add(pluginType);
            }
            Request.SetPreTypeRecords(preAssembly == null
                ? new IRecord[0]
                : XrmRecordService.RetrieveAllAndClauses(Entities.plugintype, new[] { new Condition(Fields.plugintype_.pluginassemblyid, ConditionType.Equal, Request.Id) }));

            foreach (var item in Request.GetPreTypeRecords())
            {
                var matchingItems =
                    pluginTypes.Where(pt => item.GetStringField(Fields.plugintype_.typename) == pt.TypeName);
                var matchingItem = matchingItems.Any()
                    ? matchingItems.First()
                    : null;
                if (matchingItem == null)
                {
                    //if the plugin was not loaded by the types in the assembly
                    //then create a new one
                    matchingItem = new PluginType();
                    pluginTypes.Add(matchingItem);
                    matchingItem.TypeName           = item.GetStringField(Fields.plugintype_.typename);
                    matchingItem.IsWorkflowActivity = item.GetBoolField(Fields.plugintype_.isworkflowactivity);
                }
                matchingItem.Id           = item.Id;
                matchingItem.FriendlyName = item.GetStringField(Fields.plugintype_.friendlyname);
                matchingItem.Name         = item.GetStringField(Fields.plugintype_.name);
                matchingItem.GroupName    = item.GetStringField(Fields.plugintype_.workflowactivitygroupname);
            }

            foreach (var item in pluginTypes)
            {
                var matchingItems =
                    Request.GetPreTypeRecords().Where(pt => pt.GetStringField(Fields.plugintype_.typename) == item.TypeName);
                if (matchingItems.Any())
                {
                    var matchingItem = matchingItems.First();
                    item.IsDeployed = true;
                    item.Id         = matchingItem.Id;
                    item.Name       = matchingItem.GetStringField(Fields.plugintype_.friendlyname);
                    item.GroupName  = matchingItem.GetStringField(Fields.plugintype_.workflowactivitygroupname);
                }
            }

            return(null);
        }
 protected override void ExecuteClick()
 => VisualStudioService.ShowMessage("This will close the start page in a future version of Start Page+");
示例#20
0
        protected override void OnStartup(StartupEventArgs e)
        {
            if (Process.GetProcessesByName("Cosmos.Build.Builder").Skip(1).Any())
            {
                ShowErrorMessageBox("Cannot run more than 1 instance of builder at the same time!");
                return;
            }

            var configuration = new CommandLineBuilderConfiguration(e.Args);

            BuilderConfiguration = configuration;

            MainWindow = new MainWindow();

            var visualStudioService = new VisualStudioService();

            var visualStudioInstances = visualStudioService.GetInstances();

            if (visualStudioInstances.Count == 0)
            {
                ShowErrorMessageBox("No Visual Studio instances found!");
                return;
            }

            ISetupInstance2 visualStudioInstance = null;

            if (configuration.VsPath != null)
            {
                visualStudioInstance = visualStudioInstances.FirstOrDefault(
                    i => String.Equals(
                        Path.GetFullPath(configuration.VsPath),
                        Path.GetFullPath(i.GetInstallationPath()),
                        StringComparison.Ordinal));
            }

            if (visualStudioInstance == null)
            {
                if (visualStudioInstances.Count == 1)
                {
                    visualStudioInstance = visualStudioInstances[0];
                }
                else
                {
                    var visualStudioInstanceDialogViewModel = new VisualStudioInstanceDialogViewModel(visualStudioService);
                    var visualStudioInstanceDialog          = new VisualStudioInstanceDialog();

                    visualStudioInstanceDialog.DataContext = visualStudioInstanceDialogViewModel;

                    var result = visualStudioInstanceDialog.ShowDialog();

                    if (!(result ?? false))
                    {
                        Shutdown();
                        return;
                    }

                    visualStudioInstance = visualStudioInstanceDialogViewModel.SelectedVisualStudioInstance.SetupInstance;
                }
            }

            var innoSetupService = new InnoSetupService();
            var msBuildService   = new FullMSBuildService(visualStudioInstance);

            var dependencyInstallationDialogService =
                new DialogService <DependencyInstallationDialog, DependencyInstallationDialogViewModel>(
                    () => new DependencyInstallationDialog(), MainWindow);

            var buildDefinition = new CosmosBuildDefinition(innoSetupService, msBuildService, visualStudioInstance);

            // show first, or setting owner on dialog windows may fail, as the main window may have not been shown yet.
            MainWindow.Show();
            MainWindow.DataContext = new MainWindowViewModel(dependencyInstallationDialogService, buildDefinition);

            base.OnStartup(e);
        }
示例#21
0
        public void VsixAddPortalCodeTest()
        {
            RecreatePortalData(createSecondDuplicateSite: true);
            var app = CreateAndLoadTestApplication <AddPortalCodeModule>();

            var fakeProjectName = "FakeProjectName";
            var directoryInfo   = Directory.CreateDirectory(Path.Combine(VisualStudioService.SolutionDirectory, fakeProjectName));

            VisualStudioService.SetSelectedItem(new FakeVisualStudioSolutionFolder(directoryInfo.FullName));

            var websiteName = "Fake Site 1";
            var webSite     = XrmRecordService.GetFirst(Entities.adx_website, Fields.adx_website_.adx_name, websiteName);
            var request     = new AddPortalCodeRequest
            {
                WebSite = XrmRecordService.ToLookup(webSite),
                ExportWhereFieldEmpty      = true,
                CreateFolderForWebsiteName = true
            };

            var dialog    = app.NavigateToDialog <AddPortalCodeModule, AddPortalCodeDialog>();
            var entryForm = app.GetSubObjectEntryViewModel(dialog);

            entryForm.GetLookupFieldFieldViewModel(nameof(AddPortalCodeRequest.WebSite)).SetValue(entryForm.GetLookupFieldFieldViewModel(nameof(AddPortalCodeRequest.WebSite)).ItemsSourceAsync.First(r => r.Record != null).Record);
            entryForm.GetBooleanFieldFieldViewModel(nameof(AddPortalCodeRequest.ExportWhereFieldEmpty)).Value      = true;
            entryForm.GetBooleanFieldFieldViewModel(nameof(AddPortalCodeRequest.CreateFolderForWebsiteName)).Value = true;

            var section = entryForm.GetFieldSection(AddPortalCodeRequest.Sections.RecordsToInclude);
            var func    = section.CustomFunctions.First(c => c.Id == "SELECTALL");

            func.Invoke();
            Assert.IsTrue(entryForm.GetEnumerableFieldViewModel(nameof(AddPortalCodeRequest.RecordsToExport)).GridRecords
                          .All(r => r.GetBooleanFieldFieldViewModel(nameof(AddPortalCodeRequest.PortalRecordsToExport.Selected)).Value ?? false));

            var webTemplateRow = entryForm.GetEnumerableFieldViewModel(nameof(AddPortalCodeRequest.RecordsToExport))
                                 .GridRecords
                                 .First(gr => gr.GetRecordTypeFieldViewModel(nameof(AddPortalCodeRequest.PortalRecordsToExport.RecordType)).Value.Key == Entities.adx_webtemplate);

            webTemplateRow.GetBooleanFieldFieldViewModel(nameof(AddPortalCodeRequest.PortalRecordsToExport.IncludeAll)).Value = false;
            //this now auto runs when the flag above iunchecked
            //webTemplateRow.GetEnumerableFieldViewModel(nameof(AddPortalCodeRequest.PortalRecordsToExport.RecordsToInclude)).BulkAddButton.Invoke();

            var templateRecordSelectionForm = entryForm.ChildForms.First() as MultiSelectDialogViewModel <PicklistOption>;

            templateRecordSelectionForm.ItemsSource.First().Select = true;
            templateRecordSelectionForm.ItemsSource.Last().Select  = true;
            templateRecordSelectionForm.ApplyButtonViewModel.Invoke();
            Assert.IsFalse(entryForm.ChildForms.Any());

            Assert.IsTrue(entryForm.Validate());
            entryForm.SaveButtonViewModel.Invoke();


            var responseViewModel = app.GetCompletionViewModel(dialog);
            var response          = responseViewModel.GetObject() as AddPortalCodeResponse;

            Assert.IsFalse(response.HasError);

            var rootFolder = Path.Combine(directoryInfo.FullName, websiteName);

            foreach (var typesFolder in new DirectoryInfo(rootFolder).GetDirectories())
            {
                var fileCountInDirectory = typesFolder.GetFiles().Count();
                var typeLabel            = typesFolder.Name;
                var type          = XrmRecordService.GetAllRecordTypes().First(rt => XrmRecordService.GetDisplayName(rt) == typeLabel);
                var recordsOfType = XrmRecordService.RetrieveAll(type, null);
                if (type == Entities.adx_webpage)
                {
                    //web pages have a parent and child where onluy the ch9ild is exported
                    // (multi language not implemented)
                    // + each has html, css & javascript
                    Assert.AreEqual((recordsOfType.Count() / 4) * 3, fileCountInDirectory);
                }
                else if (type == Entities.adx_webtemplate)
                {
                    Assert.AreEqual(2, fileCountInDirectory);
                }
                else
                {
                    Assert.AreEqual(recordsOfType.Count() / 2, fileCountInDirectory);
                }
            }
        }
        public override void RunFinishedExtention()
        {
            if (DestinationDirectory.EndsWith(SafeProjectName + Path.DirectorySeparatorChar + SafeProjectName))
            {
                //The projects were created under a seperate folder -- lets fix it

                //todo this appears to do something incorrect if create directory for solution was not selected

                //first move each projects up a directory
                var projectsObjects = new List <Project>();
                foreach (Project childProject in DTE.Solution.Projects)
                {
                    var fileName = childProject.FileName;
                    if (!string.IsNullOrEmpty(fileName)) //Solution Folder
                    {
                        var projectBadPath  = fileName;
                        var projectGoodPath = projectBadPath.Replace(
                            SafeProjectName + Path.DirectorySeparatorChar + SafeProjectName + Path.DirectorySeparatorChar,
                            SafeProjectName + Path.DirectorySeparatorChar);

                        DTE.Solution.Remove(childProject);

                        Directory.Move(Path.GetDirectoryName(projectBadPath), Path.GetDirectoryName(projectGoodPath));

                        DTE.Solution.AddFromFile(projectGoodPath);
                    }
                }
                //now add the references to the plugin project
                //because they got removed when we move the project folders
                Project pluginProject = null;
                foreach (Project childProject in DTE.Solution.Projects)
                {
                    var fileName = childProject.FileName;
                    if (!string.IsNullOrEmpty(fileName)) //Solution Folder
                    {
                        if (fileName.EndsWith(".Plugins.csproj"))
                        {
                            pluginProject = childProject;
                        }
                    }
                }
                foreach (Project childProject in DTE.Solution.Projects)
                {
                    var fileName = childProject.FileName;
                    if (!string.IsNullOrEmpty(fileName)) //Solution Folder
                    {
                        if (fileName.EndsWith(".Test.csproj") ||
                            fileName.EndsWith(".Console.csproj"))
                        {
                            VSProject vsProj = (VSProject)childProject.Object;
                            vsProj.References.AddProject(pluginProject);
                        }
                    }
                }
            }

            if (DestinationDirectory.EndsWith(SafeProjectName + Path.DirectorySeparatorChar + SafeProjectName))
            {
                DestinationDirectory = DestinationDirectory.Substring(0, DestinationDirectory.Length - (Path.DirectorySeparatorChar + SafeProjectName).Length);
            }

            var consoleFileName = DestinationDirectory + Path.DirectorySeparatorChar + SafeProjectName + ".Console" + Path.DirectorySeparatorChar + "Encrypt XRM Connection.bat";

            if (File.Exists(consoleFileName))
            {
                var read = File.ReadAllText(consoleFileName);
                read = read.Replace("$ext_safeprojectname$", SafeProjectName);
                File.WriteAllText(consoleFileName, read);
            }

            var visualStudioService = new VisualStudioService(DTE, useSolutionDirectory: DestinationDirectory);

            //add xrm connection and package settings to solution items
            visualStudioService.AddSolutionItem("xrmpackage.xrmsettings", XrmPackageSettings);
            if (XrmPackageSettings.Connections.Any())
            {
                visualStudioService.AddSolutionItem("solution.xrmconnection", XrmPackageSettings.Connections.First());
            }
            visualStudioService.CloseAllDocuments();

            RemoveEmptyFolders(DestinationDirectory);
        }
 protected override void ExecuteClick()
 => VisualStudioService.ExecuteCommand("File.Cloneorcheckoutcode");
示例#24
0
        public override void RunFinishedExtention()
        {
            if (DestinationDirectory.EndsWith(SafeProjectName + Path.DirectorySeparatorChar + SafeProjectName))
            {
                //The projects were created under a seperate folder -- lets fix it

                //first move each projects up a directory
                var projectsObjects = new List <Project>();
                foreach (Project childProject in DTE.Solution.Projects)
                {
                    var fileName = childProject.FileName;
                    if (!string.IsNullOrEmpty(fileName)) //Solution Folder
                    {
                        var projectBadPath  = fileName;
                        var projectGoodPath = projectBadPath.Replace(
                            SafeProjectName + Path.DirectorySeparatorChar + SafeProjectName + Path.DirectorySeparatorChar,
                            SafeProjectName + Path.DirectorySeparatorChar);

                        DTE.Solution.Remove(childProject);

                        Directory.Move(Path.GetDirectoryName(projectBadPath), Path.GetDirectoryName(projectGoodPath));

                        DTE.Solution.AddFromFile(projectGoodPath);
                    }
                }
                //now add the references to the plugin project
                //because they got removed when we move the project folders
                Project pluginProject = null;
                foreach (Project childProject in DTE.Solution.Projects)
                {
                    var fileName = childProject.FileName;
                    if (!string.IsNullOrEmpty(fileName)) //Solution Folder
                    {
                        if (fileName.EndsWith(".Plugins.csproj"))
                        {
                            pluginProject = childProject;
                        }
                    }
                }
                foreach (Project childProject in DTE.Solution.Projects)
                {
                    var fileName = childProject.FileName;
                    if (!string.IsNullOrEmpty(fileName)) //Solution Folder
                    {
                        if (fileName.EndsWith(".Test.csproj") ||
                            fileName.EndsWith(".Console.csproj"))
                        {
                            VSProject vsProj = (VSProject)childProject.Object;
                            vsProj.References.AddProject(pluginProject);
                        }
                    }
                }
            }

            if (DestinationDirectory.EndsWith(SafeProjectName + Path.DirectorySeparatorChar + SafeProjectName))
            {
                DestinationDirectory = DestinationDirectory.Substring(0, DestinationDirectory.Length - (Path.DirectorySeparatorChar + SafeProjectName).Length);
            }

            //okay so lets update the encrypt connection bat and the xrmsetting.txt files in the console project
            var consoleProjectPath = DestinationDirectory + Path.DirectorySeparatorChar + SafeProjectName + ".Console";
            var encryptBatFileName = consoleProjectPath + Path.DirectorySeparatorChar + "Encrypt XRM Connection.bat";

            if (File.Exists(encryptBatFileName))
            {
                var read = File.ReadAllText(encryptBatFileName);
                read = read.Replace("$ext_safeprojectname$", SafeProjectName);
                File.WriteAllText(encryptBatFileName, read);
            }
            var consoleConnectionFileName = consoleProjectPath + Path.DirectorySeparatorChar + "XrmSetting.txt";

            if (File.Exists(consoleConnectionFileName))
            {
                if (XrmPackageSettings != null && XrmPackageSettings.Connections != null && XrmPackageSettings.Connections.Any())
                {
                    try
                    {
                        var connection = XrmPackageSettings.Connections.First();
                        var serialise  = ObjectToJsonString(connection);
                        File.WriteAllText(consoleConnectionFileName, serialise);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error setting console application connection: " + ex.DisplayString());
                    }
                }
            }

            var visualStudioService = new VisualStudioService(DTE, useSolutionDirectory: DestinationDirectory);

            //add xrm connection and package settings to solution items
            visualStudioService.AddSolutionItem("xrmpackage.xrmsettings", XrmPackageSettings);
            if (XrmPackageSettings.Connections.Any())
            {
                visualStudioService.AddSolutionItem("solution.xrmconnection", XrmPackageSettings.Connections.First());
            }
            visualStudioService.CloseAllDocuments();

            RemoveEmptyFolders(DestinationDirectory);
        }
 protected override void ExecuteClick()
 => VisualStudioService.ExecuteCommand("File.OpenProject");
示例#26
0
        public void VsixDeployIntoFieldTest()
        {
            var fieldFilesToImport = GetFilesForFieldImport();
            var fileFilesToImport  = GetFilesForFileImport();

            //new target record to deploy into
            var targetRecordName = "TESTDEPLOYINTO";
            var targetRecord     = XrmService.GetFirst(Entities.jmcg_testentity, Fields.jmcg_testentity_.jmcg_name, targetRecordName);

            while (targetRecord != null)
            {
                XrmService.Delete(targetRecord);
                targetRecord = XrmService.GetFirst(Entities.jmcg_testentity, Fields.jmcg_testentity_.jmcg_name, targetRecordName);
            }
            targetRecord = CreateTestRecord(Entities.jmcg_testentity, new Dictionary <string, object>
            {
                { Fields.jmcg_testentity_.jmcg_name, targetRecordName }
            });

            //new target record to deploy into attachment
            var targetFileRecordName = "TESTDEPLOYINTO.css";
            var targetFileRecord     = XrmService.GetFirst(Entities.adx_webfile, XrmService.GetPrimaryNameField(Entities.adx_webfile), targetFileRecordName);

            while (targetFileRecord != null)
            {
                XrmService.Delete(targetFileRecord);
                targetFileRecord = XrmService.GetFirst(Entities.adx_webfile, XrmService.GetPrimaryNameField(Entities.adx_webfile), targetFileRecordName);
            }
            targetFileRecord = CreateTestRecord(Entities.adx_webfile, new Dictionary <string, object>
            {
                { XrmService.GetPrimaryNameField(Entities.adx_webfile), targetFileRecordName }
            });


            //create an app, deploy and verify
            VisualStudioService.SetSelectedItems(GetFilesForFieldImport().Union(GetFilesForFileImport()).Select(f => new FakeVisualStudioProjectItem(f)).ToArray());

            var testApplication = CreateAndLoadTestApplication <DeployIntoFieldModule>();
            var dialog          = testApplication.NavigateToDialog <DeployIntoFieldModule, DeployIntoFieldDialog>();

            //verify target record fields
            targetRecord = Refresh(targetRecord);
            var html       = File.ReadAllText(fieldFilesToImport.First(f => f.EndsWith("html")));
            var javascript = File.ReadAllText(fieldFilesToImport.First(f => f.EndsWith("js")));
            var css        = File.ReadAllText(fieldFilesToImport.First(f => f.EndsWith("css")));

            Assert.AreEqual(html, targetRecord.GetStringField(Fields.jmcg_testentity_.jmcg_source));
            Assert.AreEqual(javascript, targetRecord.GetStringField(Fields.jmcg_testentity_.jmcg_javascript));
            Assert.AreEqual(css, targetRecord.GetStringField(Fields.jmcg_testentity_.jmcg_css));

            //verify file attachment
            var css2base64 = Convert.ToBase64String(File.ReadAllBytes(fileFilesToImport.First(f => f.EndsWith("css"))));
            var note       = GetRegardingNotes(targetFileRecord).First();
            var noteString = note.GetStringField(Fields.annotation_.documentbody);

            Assert.AreEqual(css2base64, noteString);

            //okay lets also update the attachment as this one only created it
            //first set it as something else so when reimported it is changing
            var htmlBase64 = Convert.ToBase64String(File.ReadAllBytes(fieldFilesToImport.First(f => f.EndsWith("html"))));

            note.SetField(Fields.annotation_.documentbody, htmlBase64);
            note = UpdateFieldsAndRetreive(note, new[] { Fields.annotation_.documentbody });

            //create an app, deploy and verify
            testApplication = CreateAndLoadTestApplication <DeployIntoFieldModule>();
            dialog          = testApplication.NavigateToDialog <DeployIntoFieldModule, DeployIntoFieldDialog>();

            //verify still 1 note
            var notes = GetRegardingNotes(targetFileRecord);

            Assert.AreEqual(1, notes.Count());
            //and it was correctly updated
            noteString = notes.First().GetStringField(Fields.annotation_.documentbody);
            Assert.AreEqual(css2base64, noteString);
        }
        public void VsixGeneralAssemblyCreateUpdateAndRunPluginAssemblyTest()
        {
            //alright so this is a slightly broader example for deploying assembly
            //covering more operations updating an assembly

            var testAssemblyName = "TestAssemblyDeploy.Plugins";

            DeleteTestPluginAssembly(useAssemblyName: testAssemblyName);
            Assert.IsFalse(GetTestPluginAssemblyRecords(useAssemblyName: testAssemblyName).Any());

            var          assemblyV1        = Path.Combine(GetSolutionRootFolder().FullName, "SolutionItems", "TestAssemblyDeploy", "Version1", testAssemblyName + ".dll");
            var          assemblyV2        = Path.Combine(GetSolutionRootFolder().FullName, "SolutionItems", "TestAssemblyDeploy", "Version2", testAssemblyName + ".dll");
            var          assemblyV3        = Path.Combine(GetSolutionRootFolder().FullName, "SolutionItems", "TestAssemblyDeploy", "Version3", testAssemblyName + ".dll");
            const string testWorkflowGroup = "ScriptWorkflowGroup";
            const string inputArgumentV1   = "InputArgument1";
            const string inputArgumentV2   = "InputArgument2";

            //okay initial assembly has
            //1 * plugin
            //1 * workflow activity with 1 input argument
            var testApplication = CreateAndLoadTestApplication <DeployAssemblyModule>(loadXrmConnection: false);

            //deploy first assembly version
            VisualStudioService.SetSelectedProjectAssembly(assemblyV1);
            var deployDialog    = testApplication.NavigateToDialog <DeployAssemblyModule, DeployAssemblyDialog>();
            var deployEntryForm = testApplication.GetSubObjectEntryViewModel(deployDialog);
            var pluginGrid      = deployEntryForm.GetEnumerableFieldViewModel(nameof(DeployAssemblyRequest.PluginTypes));

            //verify correct plugin types
            Assert.AreEqual(2, pluginGrid.GridRecords.Count);
            Assert.AreEqual(1, pluginGrid.GridRecords.Count(p => p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))));
            Assert.AreEqual(1, pluginGrid.GridRecords.Count(p => !p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))));
            foreach (var item in pluginGrid.GridRecords.Where(p => p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))))
            {
                //set workflow group
                item.GetStringFieldFieldViewModel(nameof(PluginType.GroupName)).Value = testWorkflowGroup;
            }
            Assert.IsTrue(deployEntryForm.Validate());
            deployEntryForm.SaveButtonViewModel.Invoke();
            //verify no errors
            var deployResponse = deployDialog.CompletionItem as DeployAssemblyResponse;

            Assert.IsFalse(deployResponse.HasError);

            //verify assembly created with correct plugin types
            var assemblyRecords = GetTestPluginAssemblyRecords(useAssemblyName: testAssemblyName);

            Assert.AreEqual(1, assemblyRecords.Count());
            foreach (var assembly in assemblyRecords)
            {
                var pluginTypes = GetPluginTypes(assembly);
                Assert.AreEqual(2, pluginTypes.Count());

                //first assembly version only has one of 2 workflow input arguments
                var argumentWorkflow = pluginTypes.First(p => p.GetStringField(Fields.plugintype_.name) == "TestAssemblyDeployWorkflowActivity1");
                Assert.AreEqual(testWorkflowGroup, argumentWorkflow.GetStringField(Fields.plugintype_.workflowactivitygroupname));
                var inputXmlField = argumentWorkflow.GetStringField(Fields.plugintype_.customworkflowactivityinfo);
                Assert.IsTrue(inputXmlField.Contains(inputArgumentV1));
                Assert.IsFalse(inputXmlField.Contains(inputArgumentV2));
            }

            //second assembly has
            //2 * plugin
            //2 * workflow activity
            //input argument added to the workflow activity in initial deployment

            //deploy second assembly version
            VisualStudioService.SetSelectedProjectAssembly(assemblyV2);
            deployDialog    = testApplication.NavigateToDialog <DeployAssemblyModule, DeployAssemblyDialog>();
            deployEntryForm = testApplication.GetSubObjectEntryViewModel(deployDialog);
            pluginGrid      = deployEntryForm.GetEnumerableFieldViewModel(nameof(DeployAssemblyRequest.PluginTypes));
            //verify correct plugin types
            Assert.AreEqual(4, pluginGrid.GridRecords.Count);
            Assert.AreEqual(2, pluginGrid.GridRecords.Count(p => p.GetBooleanFieldFieldViewModel(nameof(PluginType.IsDeployed)).Value ?? false));
            Assert.AreEqual(2, pluginGrid.GridRecords.Count(p => p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))));
            Assert.AreEqual(2, pluginGrid.GridRecords.Count(p => !p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))));

            //set this to also refresh workflow arguments
            deployEntryForm.GetBooleanFieldFieldViewModel(nameof(DeployAssemblyRequest.TriggerWorkflowActivityRefreshes)).Value = true;
            foreach (var item in pluginGrid.GridRecords.Where(p => p.GetRecord().GetBoolField(nameof(PluginType.IsWorkflowActivity))))
            {
                //set workflow group
                item.GetStringFieldFieldViewModel(nameof(PluginType.GroupName)).Value = testWorkflowGroup;
            }
            Assert.IsTrue(deployEntryForm.Validate());
            deployEntryForm.SaveButtonViewModel.Invoke();
            //verify no errors
            deployResponse = deployDialog.CompletionItem as DeployAssemblyResponse;
            Assert.IsFalse(deployResponse.HasError);

            //verify assembly created with correct plugin types
            assemblyRecords = GetTestPluginAssemblyRecords(useAssemblyName: testAssemblyName);
            Assert.AreEqual(1, assemblyRecords.Count());
            foreach (var assembly in assemblyRecords)
            {
                var pluginTypes = GetPluginTypes(assembly);
                Assert.AreEqual(4, pluginTypes.Count());

                //second assembly version only has one of 2 workflow input arguments
                var argumentWorkflow = pluginTypes.First(p => p.GetStringField(Fields.plugintype_.name) == "TestAssemblyDeployWorkflowActivity1");
                Assert.AreEqual(testWorkflowGroup, argumentWorkflow.GetStringField(Fields.plugintype_.workflowactivitygroupname));
                var inputXmlField = argumentWorkflow.GetStringField(Fields.plugintype_.customworkflowactivityinfo);
                Assert.IsTrue(inputXmlField.Contains(inputArgumentV1));
                Assert.IsTrue(inputXmlField.Contains(inputArgumentV2));
            }

            //next assembly has added an error thrown for account plugin
            //so we need to create a plugin trigger for it on create account
            //update the assembly
            //then verify the error is thrown wher creating an account

            //add plugin trigger for peoperation create account
            testApplication.AddModule <ManagePluginTriggersModule>();
            var triggersDialog    = testApplication.NavigateToDialog <ManagePluginTriggersModule, ManagePluginTriggersDialog>();
            var triggersEntryForm = testApplication.GetSubObjectEntryViewModel(triggersDialog);
            var triggersGrid      = triggersEntryForm.GetEnumerableFieldViewModel(nameof(ManagePluginTriggersRequest.Triggers));

            //add trigger to the grid
            triggersGrid.DynamicGridViewModel.AddRowButton.Invoke();
            Assert.IsTrue(triggersEntryForm.ChildForms.Any());
            var triggerEntry = testApplication.GetSubObjectEntryViewModel(triggersEntryForm);

            triggerEntry.GetLookupFieldFieldViewModel(nameof(PluginTrigger.Plugin)).SelectedItem  = triggerEntry.GetLookupFieldFieldViewModel(nameof(PluginTrigger.Plugin)).ItemsSource.First(p => p.Name == "TestAssemblyDeployPluginRegistration");
            triggerEntry.GetLookupFieldFieldViewModel(nameof(PluginTrigger.Message)).SelectedItem = triggerEntry.GetLookupFieldFieldViewModel(nameof(PluginTrigger.Message)).ItemsSource.First(p => p.Name == "Create");
            triggerEntry.GetPicklistFieldFieldViewModel(nameof(PluginTrigger.Stage)).Value        = triggerEntry.GetPicklistFieldFieldViewModel(nameof(PluginTrigger.Stage)).ItemsSource.First(p => p.Key == PicklistOption.EnumToPicklistOption(PluginTrigger.PluginStage.PreOperationEvent).Key);
            triggerEntry.GetPicklistFieldFieldViewModel(nameof(PluginTrigger.Mode)).Value         = triggerEntry.GetPicklistFieldFieldViewModel(nameof(PluginTrigger.Mode)).ItemsSource.First(p => p.Key == PicklistOption.EnumToPicklistOption(PluginTrigger.PluginMode.Synch).Key);
            triggerEntry.GetRecordTypeFieldViewModel(nameof(PluginTrigger.RecordType)).Value      = triggerEntry.GetRecordTypeFieldViewModel(nameof(PluginTrigger.RecordType)).ItemsSource.First(p => p.Key == Entities.account);
            Assert.IsTrue(triggerEntry.Validate());
            triggerEntry.SaveButtonViewModel.Invoke();
            Assert.IsFalse(triggersEntryForm.ChildForms.Any());

            //save
            Assert.IsTrue(triggersEntryForm.Validate());
            triggersEntryForm.SaveButtonViewModel.Invoke();
            //verify no errors
            var triggersResponse = triggersDialog.CompletionItem as ManagePluginTriggersResponse;

            Assert.IsFalse(triggersResponse.HasError);

            //verify create account as we havewnt deployed the assembly throwing an error yet
            var account = CreateAccount();

            //update the assembly to the one throwing error for account create
            var updateAssemblyModule = testApplication.AddModule <UpdateAssemblyModule>();

            VisualStudioService.SetSelectedProjectAssembly(assemblyV3);
            updateAssemblyModule.DialogCommand();
            var updateAssemblyDialog = testApplication.GetNavigatedDialog <UpdateAssemblyDialog>();

            Assert.IsNull(updateAssemblyDialog.FatalException);
            var updateResponse = updateAssemblyDialog.CompletionItem as UpdateAssemblyResponse;

            Assert.IsNotNull(updateResponse.CompletionMessage);

            //verify error thrown now when creating account
            WaitTillTrue(() =>
            {
                var errorThrown = false;
                try
                {
                    account = CreateAccount();
                }
                catch (Exception)
                {
                    errorThrown = true;
                }
                return(errorThrown);
            });

            //update the assembly to the one doesnt throw an error
            VisualStudioService.SetSelectedProjectAssembly(assemblyV2);
            updateAssemblyModule.DialogCommand();
            updateAssemblyDialog = testApplication.GetNavigatedDialog <UpdateAssemblyDialog>();
            Assert.IsNull(updateAssemblyDialog.FatalException);
            updateResponse = updateAssemblyDialog.CompletionItem as UpdateAssemblyResponse;
            Assert.IsNotNull(updateResponse.CompletionMessage);

            //verify error not thrown now when creating account
            WaitTillTrue(() =>
            {
                var errorThrown = false;
                try
                {
                    account = CreateAccount();
                }
                catch (Exception)
                {
                    errorThrown = true;
                }
                return(!errorThrown);
            });

            //delete the assembly
            //if we dont delete it next time the script is run there are sometimes caching issues
            //due to deleting the creating the assembly in quick succession
            DeleteTestPluginAssembly(useAssemblyName: testAssemblyName);
            Assert.IsFalse(GetTestPluginAssemblyRecords(useAssemblyName: testAssemblyName).Any());
        }
        public void VsixCreateAndDeployPackageTest()
        {
            //clear some stuff
            DeleteAll(Entities.account);
            DeleteAll(Entities.contact);
            var tempFolder = Path.Combine(TestingFolder, "TEMP");

            if (Directory.Exists(tempFolder))
            {
                FileUtility.DeleteFiles(tempFolder);
                FileUtility.DeleteSubFolders(tempFolder);
            }

            //create and account for the deployment package
            var account         = CreateAccount();
            var packageSettings = GetTestPackageSettings();

            //set solution v2 prior to package create
            XrmService.SetField(Entities.solution, new Guid(packageSettings.Solution.Id), Fields.solution_.version, "2.0.0.0");

            //run create package dialog
            var request = CreatePackageRequest.CreateForCreatePackage(tempFolder, packageSettings.Solution);

            request.ThisReleaseVersion    = "3.0.0.0";
            request.SetVersionPostRelease = "4.0.0.0";
            request.DataToInclude         = new[]
            {
                new ExportRecordType()
                {
                    RecordType = new RecordType(Entities.account, Entities.account), Type = ExportType.AllRecords
                },
                new ExportRecordType()
                {
                    RecordType = new RecordType(Entities.contact, Entities.contact), Type = ExportType.AllRecords
                }
            };

            var createTestApplication = CreateAndLoadTestApplication <VsixCreatePackageModule>();
            var createResponse        = createTestApplication.NavigateAndProcessDialog <VsixCreatePackageModule, VsixCreatePackageDialog, ServiceResponseBase <DataImportResponseItem> >(request);

            Assert.IsFalse(createResponse.HasError);

            //verify the files created in the solution package folder
            var folder = Directory.GetDirectories(Path.Combine(VisualStudioService.SolutionDirectory, "Releases")).First();

            Assert.IsTrue(FileUtility.GetFiles(folder).First().EndsWith(".zip"));
            Assert.IsTrue(FileUtility.GetFolders(folder).First().EndsWith("Data"));
            Assert.IsTrue(FileUtility.GetFiles((FileUtility.GetFolders(folder).First())).Any());
            //+ the solution version changed
            var solution = XrmRecordService.Get(packageSettings.Solution.RecordType, packageSettings.Solution.Id);

            Assert.AreEqual("4.0.0.0", solution.GetStringField(Fields.solution_.version));

            //delete for account for recreation during import
            XrmService.Delete(account);

            //Okay now lets deploy it
            var deployRequest = new DeployPackageRequest();

            deployRequest.Connection = packageSettings.Connections.First();
            //set the package folder selected in vidsual studio
            VisualStudioService.SetSelectedItem(new FakeVisualStudioSolutionFolder(folder));

            //run the deployment dialog
            var deployTestApplication = CreateAndLoadTestApplication <VsixDeployPackageModule>();
            var deployResponse        = deployTestApplication.NavigateAndProcessDialog <VsixDeployPackageModule, DeployPackageDialog, ServiceResponseBase <DataImportResponseItem> >(deployRequest);

            Assert.IsFalse(deployResponse.HasError);

            //verify the solution dpeloyed with updated version
            solution = XrmRecordService.Get(packageSettings.Solution.RecordType, packageSettings.Solution.Id);
            Assert.AreEqual("3.0.0.0", solution.GetStringField(Fields.solution_.version));

            //account should be recreated
            account = Refresh(account);

            //Okay now lets just do the solution import it

            //set the solutoon version something
            XrmService.SetField(Entities.solution, new Guid(packageSettings.Solution.Id), Fields.solution_.version, "2.0.0.0");

            //set the solution zip selected in visual studio
            VisualStudioService.SetSelectedItem(new FakeVisualStudioProjectItem(FileUtility.GetFiles(folder).First()));

            //run the dialog
            var importSolutionRequest = new ImportSolutionRequest();

            importSolutionRequest.Connection = packageSettings.Connections.First();

            var importSolutionApplication = CreateAndLoadTestApplication <ImportSolutionModule>();
            var importSolutionResponse    = importSolutionApplication.NavigateAndProcessDialog <ImportSolutionModule, ImportSolutionDialog, ImportSolutionResponse>(importSolutionRequest);

            Assert.IsFalse(importSolutionResponse.HasError);

            //verify the solution dpeloyed with updated version
            Assert.AreEqual("3.0.0.0", solution.GetStringField(Fields.solution_.version));

            //Okay now lets just do the records import

            //delete for account for recreation during import
            XrmService.Delete(account);

            //set the xml files selected
            VisualStudioService.SetSelectedItems(FileUtility.GetFiles(FileUtility.GetFolders(folder).First()).Select(f => new FakeVisualStudioProjectItem(f)));

            //run the import records dialog
            var importRecordsRequest = new ImportRecordsRequest();

            importRecordsRequest.Connection = packageSettings.Connections.First();

            var importRecordsApplication = CreateAndLoadTestApplication <ImportRecordsModule>();
            var importRecordsResponse    = importRecordsApplication.NavigateAndProcessDialog <ImportRecordsModule, ImportRecordsDialog, ImportRecordsResponse>(importRecordsRequest);

            Assert.IsFalse(importRecordsResponse.HasError);

            //should be recreated
            account = Refresh(account);
        }
        public void VsixCreateAndDeployPackageTest()
        {
            //clear some stuff
            DeleteAll(Entities.account);
            DeleteAll(Entities.contact);
            var tempFolder = Path.Combine(TestingFolder, "TEMP");

            if (Directory.Exists(tempFolder))
            {
                FileUtility.DeleteFiles(tempFolder);
                FileUtility.DeleteSubFolders(tempFolder);
            }

            //create and account for the deployment package
            var account         = CreateAccount();
            var packageSettings = GetTestPackageSettings();

            //set solution v2 prior to package create
            XrmService.SetField(Entities.solution, new Guid(packageSettings.Solution.Id), Fields.solution_.version, "2.0.0.0");

            var app = CreateAndLoadTestApplication <VsixCreatePackageModule>();
            //run the dialog - including a redirect to enter the package settings first
            var originalConnection = HijackForPackageEntryRedirect(app);
            var dialog             = app.NavigateToDialog <VsixCreatePackageModule, VsixCreatePackageDialog>();

            VerifyPackageEntryRedirect(originalConnection, dialog);
            //okay no should be at the entry the create package details
            var packageEntry = dialog.Controller.UiItems.First() as ObjectEntryViewModel;
            //create package request
            var request = new CreatePackageRequest();

            request.HideTypeAndFolder = true;
            request.DataToInclude     = new[]
            {
                new ExportRecordType()
                {
                    RecordType = new RecordType(Entities.account, Entities.account), Type = ExportType.AllRecords
                },
                new ExportRecordType()
                {
                    RecordType = new RecordType(Entities.contact, Entities.contact), Type = ExportType.AllRecords
                }
            };
            app.EnterObject(request, packageEntry);
            //lets set explicit versions
            packageEntry.GetStringFieldFieldViewModel(nameof(CreatePackageRequest.ThisReleaseVersion)).Value    = "3.0.0.0";
            packageEntry.GetStringFieldFieldViewModel(nameof(CreatePackageRequest.SetVersionPostRelease)).Value = "4.0.0.0";

            if (!packageEntry.Validate())
            {
                throw new Exception(packageEntry.GetValidationSummary());
            }
            packageEntry.SaveButtonViewModel.Invoke();

            var createResponse = dialog.CompletionItem as ServiceResponseBase <DataImportResponseItem>;

            Assert.IsFalse(createResponse.HasError);

            //verify the files created in the solution package folder
            var folder = Directory.GetDirectories(Path.Combine(VisualStudioService.SolutionDirectory, "Releases")).First();

            Assert.IsTrue(FileUtility.GetFiles(folder).First().EndsWith(".zip"));
            Assert.IsTrue(FileUtility.GetFolders(folder).First().EndsWith("Data"));
            Assert.IsTrue(FileUtility.GetFiles((FileUtility.GetFolders(folder).First())).Any());
            //+ the solution version changed
            var solution = XrmRecordService.Get(packageSettings.Solution.RecordType, packageSettings.Solution.Id);

            Assert.AreEqual("4.0.0.0", solution.GetStringField(Fields.solution_.version));

            //delete for account for recreation during import
            XrmService.Delete(account);

            //Okay now lets deploy it
            var deployRequest = new DeployPackageRequest();

            deployRequest.Connection = packageSettings.Connections.First();
            //set the package folder selected in vidsual studio
            VisualStudioService.SetSelectedItem(new FakeVisualStudioSolutionFolder(folder));

            //run the deployment dialog
            var deployTestApplication = CreateAndLoadTestApplication <VsixDeployPackageModule>();
            var deployResponse        = deployTestApplication.NavigateAndProcessDialog <VsixDeployPackageModule, DeployPackageDialog, ServiceResponseBase <DataImportResponseItem> >(deployRequest);

            Assert.IsFalse(deployResponse.HasError);

            //verify the solution dpeloyed with updated version
            solution = XrmRecordService.Get(packageSettings.Solution.RecordType, packageSettings.Solution.Id);
            Assert.AreEqual("3.0.0.0", solution.GetStringField(Fields.solution_.version));

            //account should be recreated
            account = Refresh(account);

            //Okay now lets just do the solution import it

            //set the solutoon version something
            XrmService.SetField(Entities.solution, new Guid(packageSettings.Solution.Id), Fields.solution_.version, "2.0.0.0");

            //set the solution zip selected in visual studio
            VisualStudioService.SetSelectedItem(new FakeVisualStudioProjectItem(FileUtility.GetFiles(folder).First()));

            //run the dialog
            var importSolutionRequest = new ImportSolutionRequest();

            importSolutionRequest.Connection = packageSettings.Connections.First();

            var importSolutionApplication = CreateAndLoadTestApplication <ImportSolutionModule>();
            var importSolutionResponse    = importSolutionApplication.NavigateAndProcessDialog <ImportSolutionModule, ImportSolutionDialog, ImportSolutionResponse>(importSolutionRequest);

            Assert.IsFalse(importSolutionResponse.HasError);

            //verify the solution dpeloyed with updated version
            Assert.AreEqual("3.0.0.0", solution.GetStringField(Fields.solution_.version));

            //Okay now lets just do the records import

            //delete for account for recreation during import
            XrmService.Delete(account);

            //set the xml files selected
            VisualStudioService.SetSelectedItems(FileUtility.GetFiles(FileUtility.GetFolders(folder).First()).Select(f => new FakeVisualStudioProjectItem(f)));

            //run the import records dialog
            var importRecordsRequest = new ImportRecordsRequest();

            importRecordsRequest.Connection = packageSettings.Connections.First();

            var importRecordsApplication = CreateAndLoadTestApplication <ImportRecordsModule>();
            var importRecordsResponse    = importRecordsApplication.NavigateAndProcessDialog <ImportRecordsModule, ImportRecordsDialog, ImportRecordsResponse>(importRecordsRequest);

            Assert.IsFalse(importRecordsResponse.HasError);

            //should be recreated
            account = Refresh(account);
        }