コード例 #1
0
 /// <summary>
 /// Override this method to define the async command body te execute on the
 /// background thread
 /// </summary>
 protected override Task ExecuteAsync()
 {
     HostPackage.ActiveProject.SetDefaultAnnotationItem(this);
     return(Task.FromResult(0));
 }
コード例 #2
0
 public async Task PrepareTest(IVonkContext vonkContext)
 {
     _logger.LogDebug("VonkPluginService - About to execute $test");
     _ = await Task.FromResult(true);
 }
コード例 #3
0
        public override Task EndProcessingAsync()
        {
            _excludedCodeFiles.Clear();

            return(Task.FromResult(0));
        }
コード例 #4
0
        /// <summary>
        /// Get the view of installed packages. Use for Get-Package command.
        /// </summary>
        internal static List <PowerShellInstalledPackage> GetPowerShellPackageView(
            Dictionary <NuGetProject, IEnumerable <PackageReference> > dictionary,
            ISolutionManager SolutionManager,
            Configuration.ISettings settings)
        {
            var views = new List <PowerShellInstalledPackage>();

            foreach (var entry in dictionary)
            {
                var nugetProject = entry.Key;
                var projectName  = entry.Key.GetMetadata <string>(NuGetProjectMetadataKeys.Name);

                FolderNuGetProject          packageFolderProject = null;
                FallbackPackagePathResolver fallbackResolver     = null;

                // Build a project-specific strategy for resolving a package .nupkg path.
                if (nugetProject is INuGetIntegratedProject) // This is technically incorrect for DNX projects,
                                                             // however since that experience is deprecated we don't
                                                             // care.
                {
                    var pathContext = NuGetPathContext.Create(settings);
                    fallbackResolver = new FallbackPackagePathResolver(pathContext);
                }
                else
                {
                    var project = nugetProject as MSBuildNuGetProject;

                    if (project != null)
                    {
                        packageFolderProject = project.FolderNuGetProject;
                    }
                }

                // entry.Value is an empty list if no packages are installed.
                foreach (var package in entry.Value)
                {
                    string installPackagePath = null;
                    string licenseUrl         = null;

                    // Try to get the path to the package .nupkg on disk.
                    if (fallbackResolver != null)
                    {
                        var packageInfo = fallbackResolver.GetPackageInfo(
                            package.PackageIdentity.Id,
                            package.PackageIdentity.Version);

                        installPackagePath = packageInfo?.PathResolver.GetPackageFilePath(
                            package.PackageIdentity.Id,
                            package.PackageIdentity.Version);
                    }
                    else if (packageFolderProject != null)
                    {
                        installPackagePath = packageFolderProject.GetInstalledPackageFilePath(package.PackageIdentity);
                    }

                    // Try to read out the license URL.
                    using (var reader = GetPackageReader(installPackagePath))
                        using (var nuspecStream = reader?.GetNuspec())
                        {
                            if (nuspecStream != null)
                            {
                                var nuspecReader = new NuspecReader(nuspecStream);
                                licenseUrl = nuspecReader.GetLicenseUrl();
                            }
                        }

                    var view = new PowerShellInstalledPackage
                    {
                        Id = package.PackageIdentity.Id,
                        AsyncLazyVersions = new AsyncLazy <IEnumerable <NuGetVersion> >(
                            () => Task.FromResult <IEnumerable <NuGetVersion> >(new[] { package.PackageIdentity.Version }),
                            NuGetUIThreadHelper.JoinableTaskFactory),
                        ProjectName = projectName,
                        LicenseUrl  = licenseUrl
                    };

                    views.Add(view);
                }
            }

            return(views);
        }
コード例 #5
0
 /// <summary>
 /// Override this method to define the async command body te execute on the
 /// background thread
 /// </summary>
 protected override Task ExecuteAsync()
 {
     return(Task.FromResult(0));
 }
        public async Task GetTouchpointIDFromOutwardCodeMeetsExpectation()
        {
            // arrange
            const string theOutwardCode   = "SA38";
            const string thePostCode      = "SA38 9RD";
            const string theAdminDistrict = "E06000060";
            const string theExpectation   = "0000000456";

            var sut = MakeSUT();

            GetMock(sut.Postcode)
            .Setup(x => x.LookupOutwardCodeAsync(theOutwardCode, 10))
            .Returns(Task.FromResult <IReadOnlyCollection <string> >(new List <string> {
                thePostCode
            }));
            GetMock(sut.Postcode)
            .Setup(x => x.LookupAsync(thePostCode))
            .Returns(Task.FromResult(new PostcodeResult
            {
                Postcode = thePostCode,
                Codes    = new Codes {
                    AdminDistrict = theAdminDistrict
                }
            }));

            GetMock(sut.Authority)
            .Setup(x => x.Get(theAdminDistrict))
            .Returns(Task.FromResult <ILocalAuthority>(new LocalAuthority {
                LADCode = theAdminDistrict, TouchpointID = theExpectation
            }));

            var theLoggingScope = MakeStrictMock <IScopeLoggingContext>();

            GetMock(theLoggingScope)
            .Setup(x => x.EnterMethod("GetTouchpointIDFromOutwardCode"))
            .Returns(Task.CompletedTask);
            GetMock(theLoggingScope)
            .Setup(x => x.Information($"seeking postcode via outward code: '{theOutwardCode}'"))
            .Returns(Task.CompletedTask);
            GetMock(theLoggingScope)
            .Setup(x => x.ExitMethod("GetTouchpointIDFromOutwardCode"))
            .Returns(Task.CompletedTask);
            GetMock(theLoggingScope)
            .Setup(x => x.EnterMethod("GetTouchpointIDFromPostcode"))
            .Returns(Task.CompletedTask);
            GetMock(theLoggingScope)
            .Setup(x => x.Information($"seeking postcode '{thePostCode}'"))
            .Returns(Task.CompletedTask);
            GetMock(theLoggingScope)
            .Setup(x => x.Information($"found postcode for '{thePostCode}'"))
            .Returns(Task.CompletedTask);
            GetMock(theLoggingScope)
            .Setup(x => x.Information($"seeking local authority '{theAdminDistrict}'"))
            .Returns(Task.CompletedTask);
            GetMock(theLoggingScope)
            .Setup(x => x.Information($"found local authority '{theAdminDistrict}'"))
            .Returns(Task.CompletedTask);
            GetMock(theLoggingScope)
            .Setup(x => x.ExitMethod("GetTouchpointIDFromPostcode"))
            .Returns(Task.CompletedTask);

            // act
            var result = await sut.GetTouchpointIDFromOutwardCode(theOutwardCode, theLoggingScope);

            // assert
            Assert.Equal(theExpectation, result);
        }
コード例 #7
0
        public async Task GivenAnEverythingOperationRequest_WhenValid_ThenProperResponseShouldBeReturned()
        {
            _mediator.Send(Arg.Any <EverythingOperationRequest>(), Arg.Any <CancellationToken>()).Returns(Task.FromResult(GetEverythingOperationResponse()));

            var result = await _everythingController.PatientEverythingById(
                idParameter : "123",
                start : PartialDateTime.Parse("2019"),
                end : PartialDateTime.Parse("2020"),
                since : PartialDateTime.Parse("2021"),
                type : ResourceType.Observation.ToString(),
                ct : null) as FhirResult;

            await _mediator.Received().Send(
                Arg.Is <EverythingOperationRequest>(
                    r => string.Equals(r.EverythingOperationType, ResourceType.Patient.ToString(), StringComparison.Ordinal) &&
                    string.Equals(r.ResourceId.ToString(), "123", StringComparison.OrdinalIgnoreCase) &&
                    string.Equals(r.Start.ToString(), "2019", StringComparison.Ordinal) &&
                    string.Equals(r.End.ToString(), "2020", StringComparison.Ordinal) &&
                    string.Equals(r.Since.ToString(), "2021", StringComparison.Ordinal) &&
                    string.Equals(r.ResourceTypes, ResourceType.Observation.ToString(), StringComparison.Ordinal) &&
                    r.ContinuationToken == null),
                Arg.Any <CancellationToken>());

            _mediator.ClearReceivedCalls();

            var bundleResource = (result?.Result as ResourceElement)?.ResourceInstance as Bundle;

            Assert.Equal(System.Net.HttpStatusCode.OK, result?.StatusCode);
            Assert.Equal(Bundle.BundleType.Searchset, bundleResource?.Type);
        }
コード例 #8
0
        private void SetupDataStoreToReturnDummyResourceWrapper()
        {
            ResourceElement patientResourceElement = Samples.GetDefaultPatient();
            Patient         patientResource        = patientResourceElement.ToPoco <Patient>();
            RawResource     rawResource            = new RawResource(new FhirJsonSerializer().SerializeToString(patientResource), FhirResourceFormat.Json, isMetaSet: false);

            ResourceWrapper dummyResourceWrapper = new ResourceWrapper(
                patientResourceElement.Id,
                versionId: "1",
                patientResourceElement.InstanceType,
                rawResource,
                request: null,
                patientResourceElement.LastUpdated ?? Clock.UtcNow,
                deleted: false,
                searchIndices: null,
                compartmentIndices: null,
                lastModifiedClaims: null);

            _fhirDataStore.GetAsync(Arg.Any <ResourceKey>(), _cancellationToken).Returns(Task.FromResult(dummyResourceWrapper));
        }
コード例 #9
0
 /// <summary>
 /// Sets the active project to the current project file
 /// </summary>
 protected override Task ExecuteAsync()
 {
     HostPackage.Solution.SetActiveProject(ItemPath);
     return(Task.FromResult(0));
 }
コード例 #10
0
        public CreateTaskSuccessShould()
        {
            _logger     = new Mock <ILogger <TasksController> >();
            _dispatcher = new Mock <IDispatcher>();

            _dispatcher.Setup(r => r.PushAsync(_cmdHandler, this._cmd))
            .Callback((ICommandHandlerAsync <CreateTaskCmd> h, CreateTaskCmd c) => c.Result = this._response).Returns(Task.FromResult((object)null));

            _controller = new TasksController(_logger.Object, _dispatcher.Object, null);
        }
コード例 #11
0
 protected override Task ButtonCallbackAsync(object sender, EventArgs e)
 {
     return(Task.FromResult(false));
 }
コード例 #12
0
        public async Task NestedRunResultLoggingTestAsync()
        {
            var actions = new ActionProfileOptions[3];

            actions[0] = new ActionProfileOptions {
                Name = "Exchange Soul"
            };
            actions[0].Steps.Add(new ExecuteStep {
                Environment = StepEnvironment.Remote, Executable = "cleanup", Arguments = "--skip"
            });
            actions[1] = new ActionProfileOptions {
                Name = "Sign Contract"
            };
            actions[1].Steps.Add(new ExecuteStep {
                Environment = StepEnvironment.Remote, Executable = "obtain-contract", Arguments = "-i -mm"
            });
            actions[1].Steps.Add(new RunActionStep {
                Name = "Exchange Soul"
            });
            actions[2] = new ActionProfileOptions {
                Name = "Transform"
            };
            actions[2].Steps.Add(new RunActionStep {
                Name = "Sign Contract"
            });
            actions[2].Steps.Add(new CopyFileStep {
                Direction = FileCopyDirection.LocalToRemote, FailIfNotModified = true, TargetPath = "incubator", SourcePath = "soul"
            });

            var evaluator = new Mock <IMacroEvaluator>();

            evaluator.Setup(e => e.EvaluateAsync(It.IsAny <string>())).Returns <string>(s => Task.FromResult <Result <string> >(s));

            var env = new ActionEvaluationEnvironment("", "", false, new DebugServer.IPC.CapabilityInfo(default, default, default), actions);
コード例 #13
0
 public async Task PostHandlerTest(IVonkContext vonkContext)
 {
     _logger.LogDebug("VonkPluginService - PostHandler $test");
     _ = await Task.FromResult(true);
 }
コード例 #14
0
 /// <summary>
 /// Override this method to define the async command body te execute on the
 /// background thread
 /// </summary>
 protected override Task ExecuteAsync()
 {
     SpectrumProject?.SetDefaultTapeItem(this);
     return(Task.FromResult(0));
 }
コード例 #15
0
 public System.Threading.Tasks.Task <IList <string> > GetWidgetZonesAsync()
 {
     return(Task.FromResult <IList <string> >(new List <string> {
         "productdetails_overview_bottom"
     }));
 }
コード例 #16
0
 protected void PrepareActionSheet(bool confirm)
 {
     DialogService.ConfirmDestructiveAction(ActionType.DeleteExistingTimeEntry)
     .Returns(Task.FromResult(confirm));
 }
コード例 #17
0
ファイル: CookiecutterPackage.cs プロジェクト: PeezoSlug/PTVS
 protected override Task <object> InitializeToolWindowAsync(Type toolWindowType, int id, CancellationToken cancellationToken)
 => toolWindowType == typeof(CookiecutterToolWindow) ? Task.FromResult <object>(this) : base.InitializeToolWindowAsync(toolWindowType, id, cancellationToken);
コード例 #18
0
        public async Task GivenResourceDoesNotExist_WhenHandle_ThenResourceNotFoundExceptionIsThrown()
        {
            _fhirDataStore.GetAsync(Arg.Any <ResourceKey>(), _cancellationToken).Returns(Task.FromResult <ResourceWrapper>(null));

            var request = GetReindexRequest(HttpGetName);
            await Assert.ThrowsAsync <ResourceNotFoundException>(() => _reindexHandler.Handle(request, _cancellationToken));
        }
コード例 #19
0
        /// <inheritdoc />
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress);

            this.AddService(typeof(SSqliteVisualizerService), (sc, ct, st) => Task.FromResult <object>(new SqliteVisualizerService()), true);
        }
コード例 #20
0
 /// <summary>
 /// Override this method to define the async command body te execute on the
 /// background thread
 /// </summary>
 protected override Task ExecuteAsync()
 {
     CompileTests();
     return(Task.FromResult(0));
 }
コード例 #21
0
 private Task SomeAsync(int i)
 {
     Debug.WriteLine(i);
     return(Task.FromResult(0));
 }
コード例 #22
0
 public override Task BeginProcessingAsync()
 {
     return(Task.FromResult(0));
 }
コード例 #23
0
 /// <summary>
 /// Override this method to define the action to execute on the main
 /// thread of Visual Studio -- finally
 /// </summary>
 protected override Task FinallyOnMainThread()
 {
     Package.CodeManager.CompilatioInProgress = false;
     return(Task.FromResult(0));
 }
コード例 #24
0
ファイル: CronTasksPlugin.cs プロジェクト: abcwarehouse/nop
 public System.Threading.Tasks.Task <IList <string> > GetWidgetZonesAsync()
 {
     return(Task.FromResult <IList <string> >(new List <string> {
         AdminWidgetZones.ScheduleTaskListButtons
     }));
 }
コード例 #25
0
ファイル: ContactUsWidget.cs プロジェクト: abcwarehouse/nop
 public System.Threading.Tasks.Task <IList <string> > GetWidgetZonesAsync()
 {
     return(Task.FromResult <IList <string> >(new List <string> {
         "topic_page_after_body"
     }));
 }
コード例 #26
0
        Task IJob.Execute(IJobExecutionContext context)
        {
            try
            {
                //get job parameters
                JobDataMap dataMap = context.JobDetail.JobDataMap;                        //get the datamap from the Quartz job

                var job = (SitecronJob)dataMap[SitecronConstants.ParamNames.SitecronJob]; //get the SitecronJob from the job definition
                if (job == null)
                {
                    throw new Exception("Unable to load SiteCron Job Definition");
                }

                string   contextDbName = Settings.GetSetting(SitecronConstants.SettingsNames.SiteCronContextDB, "master");
                Database contextDb     = Factory.GetDatabase(contextDbName);

                Item jobItem = contextDb.GetItem(new ID(job.SitecoreScheduleJob));
                if (jobItem == null)
                {
                    throw new Exception("Unable to load Sitecore Schedule Job Item: " + job.SitecoreScheduleJob);
                }

                ScheduleItem scheduleItem = new ScheduleItem(jobItem);
                if (scheduleItem == null)
                {
                    throw new Exception("Invalid Sitecore Job item specified: " + job.SitecoreJobType);
                }

                Type type = Type.GetType(scheduleItem.CommandItem.InnerItem[SitecronConstants.FieldNames.Type]);
                if (type == null)
                {
                    throw new Exception("Unable to resolve the Sitecore Job Type specified: " + job.SitecoreJobType);
                }

                object instance = Activator.CreateInstance(type);
                if (instance == null)
                {
                    throw new Exception("Unable to instantiate the Sitecore Job Type specified: " + job.SitecoreJobType);
                }

                DefaultJobOptions options = new DefaultJobOptions(job.SitecoreJobName, job.SitecoreJobCategory, job.SitecoreJobSiteName, instance, scheduleItem.CommandItem.InnerItem[SitecronConstants.FieldNames.Method], new object[] { scheduleItem.Items, scheduleItem.CommandItem, scheduleItem });

                ThreadPriority jobPriority;
                if (Enum.TryParse <ThreadPriority>(job.SitecoreJobPriority, out jobPriority))
                {
                    options.Priority = jobPriority;
                }
                else
                {
                    options.Priority = ThreadPriority.Normal;
                }

                JobManager.Start(options);

                context.JobDetail.JobDataMap.Put(SitecronConstants.ParamNames.SitecronJobLogData, "Sitecron: RunAsSitecoreJob: Done");
            }
            catch (Exception ex)
            {
                Log.Error("SiteCron: SitecoreScheduleCommandJob: ERROR something went wrong - " + ex.Message, ex, this);
                context.JobDetail.JobDataMap.Put(SitecronConstants.ParamNames.SitecronJobLogData, "Sitecron: SitecoreScheduleCommandJob: ERROR something went wrong - " + ex.Message);
            }

            return(Task.FromResult <object>(null));
        }
コード例 #27
0
 /// <summary>
 /// Override this method to define the action to execute on the main
 /// thread of Visual Studio -- finally
 /// </summary>
 protected virtual Task FinallyOnMainThreadAsync() => Task.FromResult(0);
コード例 #28
0
 /// <summary>
 /// We conclude the command with sending the message to
 /// notify any views that use the annotation file
 /// </summary>
 protected override Task FinallyOnMainThreadAsync()
 {
     SpectNetPackage.Default.CodeManager.RaiseAnnotationFileChanged();
     return(Task.FromResult(0));
 }
コード例 #29
0
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await base.InitializeAsync(cancellationToken, progress);

            // When initialized asynchronously, we *may* be on a background thread at this point.
            // Do any initialization that requires the UI thread after switching to the UI thread.
            // Otherwise, remove the switch to the UI thread if you don't need it.
            await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            this.AddService(typeof(IStatusBarService), async(container, token, type) =>
            {
                await JoinableTaskFactory.SwitchToMainThreadAsync(token);

                if (!(await GetServiceAsync(typeof(SVsStatusbar)) is IVsStatusbar statusBar))
                {
                    return(null);
                }

                var service = new StatusBarService(statusBar);
                return(await Task.FromResult(service));
            });

            this.AddService(typeof(ILogger), async(container, token, type) =>
            {
                await JoinableTaskFactory.SwitchToMainThreadAsync(token);
                if (!(await GetServiceAsync(typeof(SVsOutputWindow)) is IVsOutputWindow outputWindow))
                {
                    return(null);
                }

                if (!(await GetServiceAsync(typeof(DTE)) is DTE2 dte))
                {
                    return(null);
                }

                var eventSource = nameof(PowerClean);
                try
                {
                    // searching the source throws a security exception ONLY if not exists!
                    if (EventLog.SourceExists(eventSource))
                    { // no exception until yet means the user as admin privilege
                        EventLog.CreateEventSource(eventSource, "Application");
                    }
                }
                catch (SecurityException)
                {
                    eventSource = "Application";
                }

                var loggerConfig = new LoggerConfiguration()
                                   .MinimumLevel.Information()
                                   .WriteTo.VisualStudio(outputWindow)          //TODO make config so it only logs some things in verbose
                                   .WriteTo.EventLog(eventSource, Application); //TODO remember to handle outputTemplate

                #region Config
                //var solutionFolder = dte.Solution.GetRootFolder();

                //var powerCleanConfig = $"{dte.Solution.FileName}.powerclean.json";

                //var powerCleanConfigFile = Path.Combine(solutionFolder, powerCleanConfig);

                //EnsureCreatedConfig(powerCleanConfigFile);

                //if (File.Exists(powerCleanConfigFile))
                //{
                //  var configuration = new ConfigurationBuilder()
                //      .SetBasePath(solutionFolder)
                //      .AddJsonFile(powerCleanConfig)
                //      .Build();
                //  loggerConfig.ReadFrom.Configuration(configuration);
                //}
                #endregion

                return(await Task.FromResult(Log.Logger = loggerConfig.CreateLogger()));
            });

            this.AddService(typeof(IPowerShellService), async(container, token, type) =>
            {
                await JoinableTaskFactory.SwitchToMainThreadAsync(token);

                if (!(await GetServiceAsync(typeof(SVsOutputWindow)) is IVsOutputWindow outputWindow))
                {
                    return(null);
                }

                if (!(await GetServiceAsync(typeof(DTE)) is DTE2 dte))
                {
                    return(null);
                }
                Assumes.Present(dte);
                if (!(await GetServiceAsync(typeof(IStatusBarService)) is IStatusBarService statusBarService))
                {
                    return(null);
                }
                if (!(await GetServiceAsync(typeof(ILogger)) is ILogger logger))
                {
                    return(null);
                }
                var service = new PowerShellService(dte, statusBarService, outputWindow, logger);
                return(await Task.FromResult(service));
            });

            await PowerCleanSolutionCommand.InitializeAsync(this);

            await PowerCleanProjectCommand.InitializeAsync(this);

            Log.Logger.Here();
        }