public void Execute(TaskExecutionContext context, CancellationToken cancellationToken = null) { PSAssert.Validate(!IsCoroutine, "Execute called on coroutine"); _cancellationToken = cancellationToken ?? new CancellationToken(); DoExecute(context); }
public IEnumerator ExecuteCoroutine(TaskExecutionContext context, CancellationToken cancellationToken = null) { PSAssert.Validate(IsCoroutine, "ExecuteCoroutine called on action"); _cancellationToken = cancellationToken ?? new CancellationToken(); return DoExecuteCoroutine(context); }
public void AttachBW_MissingBinaryFiles_TaskFails() { // Create a valid setup, then delete one of the required files each time // and check that the task fails // Arrange string testFolder = TestUtils.GetTestSpecificFolderName(this.TestContext); for (int i = 0; i < TaskExecutionContext.RequiredFileNames.Length; i++) { // Clean up after the previous iteration if (Directory.Exists(testFolder)) { Directory.Delete(testFolder, true); } Directory.CreateDirectory(testFolder); DummyBuildEngine dummyEngine = new DummyBuildEngine(); TaskExecutionContext taskContext = new TaskExecutionContext(testFolder, testFolder, testFolder, 0 /* returns failure code */ ); string missingFilePath = taskContext.RequiredFilePaths[i]; File.Delete(missingFilePath); // delete one of the required files AttachBuildWrapper testSubject = CreateTestSubject(dummyEngine, testFolder, testFolder); // Act and assert bool success = testSubject.Execute(); Assert.IsFalse(success, "Expecting the task execution to fail"); dummyEngine.AssertSingleErrorExists(missingFilePath); } }
public ProcessResult Execute(ProcessInfo processInfo, ProjectItem item, TaskExecutionContext context) { var outputFile = context.GeneratePathInWorkingDirectory(item.NameOrType + ".log"); if ((this.Item == null) || (this.Context == null)) { return this.Execute(processInfo, item.Project.Name, item.NameOrType, outputFile); } Assert.AreEqual(this.FileName, processInfo.FileName); var actual = processInfo.Arguments == null ? null : processInfo.Arguments.ToString(); Assert.AreEqual(this.Arguments, actual); Assert.AreEqual(this.WorkingDirectory, processInfo.WorkingDirectory); Assert.AreSame(this.Item, item); Assert.AreEqual(this.Context, context); var fileSystemMock = new Mock<IFileSystem>(); fileSystemMock.Setup(fs => fs.OpenFileForRead(outputFile)).Returns(new MemoryStream()); var result = new ProcessResult( fileSystemMock.Object, outputFile, this.ExitCode, this.TimedOut, this.Failed); return result; }
/** * Implements {@link Task#execute(TaskExecutionContext)}, launching the * {@link Runnable#run()} method on the wrapped object. */ public override void Execute(TaskExecutionContext context) { if (_runnable != null) _runnable.Run(); else _actionRunnable(context); }
/// <summary> /// Executes this task. /// </summary> /// <param name="context">The context.</param> /// <returns> /// The child tasks to execute. /// </returns> protected override IEnumerable<Task> OnRun(TaskExecutionContext context) { var block = this.GetSourceControlBlock(); var parameters = new GetSourceParameters(); logger.Debug("Getting source for '{0}'", this.NameOrType); block.GetSource(parameters); return null; }
public static TaskExecutionContext Initialise(Project project) { var instance = new TaskExecutionContext( new TaskExecutionParameters { Project = project }); return instance; }
protected override IEnumerable<Task> OnRun(TaskExecutionContext context) { if (this.OnRunAction != null) { return this.OnRunAction(context); } throw new NotImplementedException(); }
protected override IEnumerator DoExecuteCoroutine(TaskExecutionContext context, BackendConnection connection) { PSDebug.Log("Execute BackendUpdateTask"); yield return connection.DoPostData( connection.UserAction("update"), _serializedGameState, context.CancellationToken, false ); }
/// <summary> /// Executes this task. /// </summary> /// <param name="context">The context.</param> /// <returns> /// The child tasks to execute. /// </returns> protected override IEnumerable<Task> OnRun(TaskExecutionContext context) { foreach (var file in this.Files) { logger.Info("Merging file '{0}'", file.File); context.ImportFile(file.File, file.Delete); } return null; }
public ProcessExecutorStub( string fileName, string args, string workingDir, ProjectItem item, TaskExecutionContext context) { this.FileName = fileName; this.Arguments = args; this.WorkingDirectory = workingDir; this.Item = item; this.Context = context; }
public void ConstructorSetsProperties() { var request = new IntegrationRequest("Test"); var project = new Project(); var context = new TaskExecutionContext(new TaskExecutionParameters { IntegrationRequest = request, Project = project }); Assert.AreSame(request, context.Request); Assert.AreSame(project, context.Project); Assert.IsNotNull(context.ModificationSets); }
protected override IEnumerator DoExecuteCoroutine(TaskExecutionContext context) { var headers = context.Get<Dictionary<string, string>>(HeaderKey); var url = (string)context[UrlKey]; using (var www = new WWW(url, null, headers)) { var progressReporter = ProgressCallback(_progressKey, context.OnProgress); yield return WwwHelper.GetResponse(www, context.CancellationToken, (string)context[HashKey], progressReporter); context[ResultKey] = www.text; } }
protected override IEnumerator DoExecuteCoroutine(TaskExecutionContext context) { var url = (string)context[UrlKey]; PSDebug.Log("Start Download: {0}", url); using (var www = new WWW(url)) { var progressReporter = ProgressCallback(_progressKey, context.OnProgress); yield return WwwHelper.GetResponse(www, context.CancellationToken, (string)context[HashKey], progressReporter); var target = (string)context[TargetPathKey]; FileHelper.WriteFileAtomic(target, www.bytes, deleteOnError: true); } }
/// <summary> /// Executes this task. /// </summary> /// <param name="context">The context.</param> /// <returns> /// The child tasks to execute. /// </returns> protected override IEnumerable<Task> OnRun(TaskExecutionContext context) { logger.Info("Running sequence '{0}' with {1} task(s)", this.NameOrType, this.Tasks.Count); var count = 0; foreach (var task in this.Tasks) { logger.Info("Running child task {0} in '{1}'", count++, this.NameOrType); yield return task; } yield break; }
/// <summary> /// Executes this task. /// </summary> /// <param name="context">The context.</param> /// <returns> /// The child tasks to execute. /// </returns> protected override IEnumerable<Task> OnRun(TaskExecutionContext context) { logger.Info("Sending force build to '{0}'", this.ProjectName); if (string.IsNullOrEmpty(this.ServerAddress)) { this.SendLocalRequest(context); } else { this.SendRemoteRequest(context); } return null; }
/// <summary> /// Executes this task. /// </summary> /// <param name="context">The context.</param> /// <returns> /// The child tasks to execute. /// </returns> protected override IEnumerable<Task> OnRun(TaskExecutionContext context) { logger.Info("Building MSBuild project '{0}'", this.ProjectFile); var info = InitialiseProcess(); var result = this.ProcessExecutor.Execute(info, this, context); if (!result.Succeeded) { context.CurrentStatus = IntegrationStatus.Failure; } else { context.CurrentStatus = IntegrationStatus.Success; } return null; }
public void CompleteClosesWriter() { var writerMock = new Mock<XmlWriter>(MockBehavior.Strict); writerMock.Setup(w => w.WriteEndDocument()).Verifiable(); writerMock.Setup(w => w.Close()).Verifiable(); writerMock.MockWriteElementString("finish", "2010-01-01T12:01:01"); writerMock.MockWriteElementString("status", "Success"); var clockMock = new Mock<IClock>(MockBehavior.Strict); clockMock.Setup(c => c.Now).Returns(new DateTime(2010, 1, 1, 12, 1, 1)); var context = new TaskExecutionContext( new TaskExecutionParameters { XmlWriter = writerMock.Object, Clock = clockMock.Object }); Assert.IsFalse(context.IsCompleted); context.Complete(); writerMock.Verify(); Assert.IsTrue(context.IsCompleted); }
public void CompleteDoesNothingIfAlreadyClosed() { var action = 0; var writerMock = new Mock<XmlWriter>(MockBehavior.Strict); writerMock.Setup(w => w.WriteEndDocument()).Callback(() => action++); writerMock.Setup(w => w.Close()).Callback(() => action++); writerMock.MockWriteElementString("finish", "2010-01-01T12:01:01"); writerMock.MockWriteElementString("status", "Success"); var clockMock = new Mock<IClock>(MockBehavior.Strict); clockMock.Setup(c => c.Now).Returns(new DateTime(2010, 1, 1, 12, 1, 1)); var context = new TaskExecutionContext( new TaskExecutionParameters { XmlWriter = writerMock.Object, Clock = clockMock.Object }); context.Complete(); context.Complete(); Assert.AreEqual(2, action); }
/** * Implements {@link Task#execute(TaskExecutionContext)}. It uses Java * reflection to load the given class and call the given static method with * the supplied arguments. */ public override void Execute(TaskExecutionContext context) { // Loads the class. Type classObject; try { classObject = Type.GetType(className); } catch (Exception e) { throw new SystemException("Cannot load class " + className, e); } // Finds the method. MethodInfo methodObject; try { Type[] argTypes = new Type[args.Length]; Array.CreateInstance(typeof(string), argTypes.Length); methodObject = classObject.GetMethod(methodName, argTypes); } catch (Exception e) { throw new SystemException("Cannot find a " + methodName + "(String[]) method in class " + className, e); } if (!methodObject.IsStatic) { throw new SystemException("The method " + methodName + "(String[]) of the class " + className + " is not static"); } // Invokes the method. try { methodObject.Invoke(null, args); } catch (Exception e) { throw new SystemException("Failed to invoke the static method " + methodName + "(String[]) of the class " + className, e); } }
private ICancelable ExecuteCurrent(TaskExecutionContext context, Action<TaskExecutionContext> successCallback) { var task = _tasks.RemoveAndGet(0); if (_tasks.IsEmpty()) { context.OnSuccess = successCallback; } else { context.OnSuccess = result => { if (!_cancellationToken.IsCanceled) { ExecuteCurrent(context, successCallback); } }; } return TaskExecutor.Execute(task, context); }
/// <summary> /// Starts a new <see cref="TaskExecutionContext"/>. /// </summary> /// <param name="project">The project.</param> /// <param name="request">The request.</param> /// <returns> /// The new <see cref="TaskExecutionContext"/>. /// </returns> public TaskExecutionContext StartNew(Project project, IntegrationRequest request) { logger.Debug("Starting execution context for project '{0}", project.Name); var buildName = this.Clock.Now.ToString("yyyyMMddHHmmss"); var logFile = TaskExecutionContext.GenerateArtifactFileName(project, buildName, "build.log"); this.FileSystem.EnsureFolderExists(Path.GetDirectoryName(logFile)); var writer = this.FileSystem.CreateXmlWriter(logFile); writer.WriteStartElement("project"); writer.WriteAttributeString("name", project.Name); writer.WriteElementString("start", this.Clock.Now.ToString("s")); var parameters = new TaskExecutionParameters { XmlWriter = writer, FileSystem = this.FileSystem, Clock = this.Clock, IntegrationRequest = request, Project = project, BuildName = buildName }; var context = new TaskExecutionContext(parameters); return context; }
public void CompleteClosesElementIfChild() { var writerMock = new Mock<XmlWriter>(MockBehavior.Loose); writerMock.Setup(w => w.WriteEndElement()).Verifiable(); writerMock.Setup(w => w.WriteEndDocument()).Throws(new AssertionException("WriteEndDocument called")); var clockMock = new Mock<IClock>(MockBehavior.Strict); clockMock.Setup(c => c.Now).Returns(new DateTime(2010, 1, 1, 12, 1, 1)); var context = new TaskExecutionContext( new TaskExecutionParameters { XmlWriter = writerMock.Object, Clock = clockMock.Object }); var child = context.StartChild(new Comment()); child.Complete(); writerMock.Verify(); }
/// <summary> /// Executes this task. /// </summary> /// <param name="context">The context.</param> /// <returns> /// The child tasks to execute. /// </returns> protected override IEnumerable <Task> OnRun(TaskExecutionContext context) { throw new NotImplementedException(); }
public override async Task ExecuteAsync(TaskExecutionContext ctx) { var count = 0; var numDeleted = 0; var numAdded = 0; var pageSize = 500; var categoryQuery = _categoryRepository.TableUntracked.Expand(x => x.RuleSets); if (ctx.Parameters.ContainsKey("CategoryIds")) { var categoryIds = ctx.Parameters["CategoryIds"].ToIntArray(); categoryQuery = categoryQuery.Where(x => categoryIds.Contains(x.Id)); numDeleted = _productCategoryRepository.Context.ExecuteSqlCommand( "Delete From [dbo].[Product_Category_Mapping] Where [CategoryId] In ({0}) And [IsSystemMapping] = 1", false, null, string.Join(",", categoryIds)); } else { numDeleted = _productCategoryRepository.Context.ExecuteSqlCommand("Delete From [dbo].[Product_Category_Mapping] Where [IsSystemMapping] = 1"); } var categories = await categoryQuery .Where(x => x.Published && !x.Deleted && x.RuleSets.Any(y => y.IsActive)) .ToListAsync(); using (var scope = new DbContextScope(ctx: _productCategoryRepository.Context, autoDetectChanges: false, validateOnSave: false, hooksEnabled: false, autoCommit: false)) { foreach (var category in categories) { var ruleSetProductIds = new HashSet <int>(); ctx.SetProgress(++count, categories.Count, $"Add product mappings for category \"{category.Name.NaIfEmpty()}\"."); // Execute active rule sets and collect product ids. foreach (var ruleSet in category.RuleSets.Where(x => x.IsActive)) { if (ctx.CancellationToken.IsCancellationRequested) { return; } if (_ruleFactory.CreateExpressionGroup(ruleSet, _productRuleProvider) is SearchFilterExpression expression) { var pageIndex = -1; while (true) { // Do not touch searchResult.Hits. We only need the product identifiers. var searchResult = _productRuleProvider.Search(new SearchFilterExpression[] { expression }, ++pageIndex, pageSize); ruleSetProductIds.AddRange(searchResult.HitsEntityIds); if (pageIndex >= (searchResult.TotalHitsCount / pageSize)) { break; } } } } // Add mappings. if (ruleSetProductIds.Any()) { foreach (var chunk in ruleSetProductIds.Slice(500)) { if (ctx.CancellationToken.IsCancellationRequested) { return; } foreach (var productId in chunk) { _productCategoryRepository.Insert(new ProductCategory { ProductId = productId, CategoryId = category.Id, IsSystemMapping = true }); ++numAdded; } await scope.CommitAsync(); } try { _productCategoryRepository.Context.DetachEntities <ProductCategory>(); } catch { } } } } Debug.WriteLineIf(numDeleted > 0 || numAdded > 0, $"Deleted {numDeleted} and added {numAdded} product mappings for {categories.Count} categories."); }
public async Task Run(TaskExecutionContext ctx, CancellationToken cancelToken = default) { //var count = 0; var numDeleted = 0; var numAdded = 0; var numCategories = 0; var pageSize = 500; var pageIndex = -1; var categoryIds = ctx.Parameters.ContainsKey("CategoryIds") ? ctx.Parameters["CategoryIds"].ToIntArray() : null; // Hooks are enabled because search index needs to be updated. using (var scope = new DbContextScope(_db, autoDetectChanges: false, hooksEnabled: true, deferCommit: true)) { // Delete existing system mappings. var deleteQuery = _db.ProductCategories.Where(x => x.IsSystemMapping); if (categoryIds != null) { deleteQuery = deleteQuery.Where(x => categoryIds.Contains(x.CategoryId)); } await deleteQuery.BatchDeleteAsync(cancelToken); // Insert new product category mappings. var categoryQuery = _db.Categories .Include(x => x.RuleSets) .AsNoTracking(); if (categoryIds != null) { categoryQuery = categoryQuery.Where(x => categoryIds.Contains(x.Id)); } var categories = await categoryQuery .Where(x => x.Published && x.RuleSets.Any(y => y.IsActive)) .ToListAsync(cancelToken); numCategories = categories.Count; foreach (var category in categories) { var ruleSetProductIds = new HashSet <int>(); // TODO: (mg) (core) Complete ProductRuleEvaluatorTask (TaskExecutionContext required). //ctx.SetProgress(++count, categories.Count, $"Add product mappings for category \"{category.Name.NaIfEmpty()}\"."); // Execute active rule sets and collect product ids. foreach (var ruleSet in category.RuleSets.Where(x => x.IsActive)) { if (cancelToken.IsCancellationRequested) { return; } var expressionGroup = await _ruleService.CreateExpressionGroupAsync(ruleSet, (IRuleVisitor)_productRuleProvider); if (expressionGroup is SearchFilterExpression expression) { pageIndex = -1; while (true) { // Do not touch searchResult.Hits. We only need the product identifiers. var searchResult = await _productRuleProvider.SearchAsync(new[] { expression }, ++pageIndex, pageSize); ruleSetProductIds.AddRange(searchResult.HitsEntityIds); if (pageIndex >= (searchResult.TotalHitsCount / pageSize)) { break; } } } } // Add mappings. if (ruleSetProductIds.Any()) { foreach (var chunk in ruleSetProductIds.Slice(500)) { if (cancelToken.IsCancellationRequested) { return; } foreach (var productId in chunk) { _db.ProductCategories.Add(new ProductCategory { ProductId = productId, CategoryId = category.Id, IsSystemMapping = true }); ++numAdded; } await scope.CommitAsync(cancelToken); } try { scope.DbContext.DetachEntities <ProductCategory>(); } catch { } } } } Debug.WriteLineIf(numDeleted > 0 || numAdded > 0, $"Deleted {numDeleted} and added {numAdded} product mappings for {numCategories} categories."); }
public void ExecuteWithProjectItemGeneratesTheRightArguments() { var info = new ProcessInfo("Test"); var item = new Comment { Project = new Project("Test") }; var context = new TaskExecutionContext( new TaskExecutionParameters { Project = item.Project }); var logFile = context.GeneratePathInWorkingDirectory("Comment.log"); var executor = new ProcessExecutorOverride { OnExecute = (pi, p, i, o) => { Assert.AreSame(info, pi); Assert.AreEqual("Test", p); Assert.AreEqual("Comment", i); Assert.AreEqual(logFile, o); return null; } }; executor.Execute(info, item, context); }
/// <summary> /// Executes this task. /// </summary> /// <param name="context">The context.</param> /// <returns> /// The child tasks to execute. /// </returns> protected override IEnumerable <Task> OnRun(TaskExecutionContext context) { logger.Info("Adding comment to the build log"); context.AddEntryToBuildLog(this.Text); return(null); }
public override async Task ExecuteAsync(TaskExecutionContext ctx) { //60*24 = 1 day var olderThanMinutes = 1440; // TODO: move to settings await _customerService.DeleteGuestCustomersAsync(null, DateTime.UtcNow.AddMinutes(-olderThanMinutes), true); }
public void Execute(TaskExecutionContext ctx) { FileSystemHelper.TempCleanup(); }
private void CreateFeed(FeedFileCreationContext fileCreation, TaskExecutionContext taskContext) { var xmlSettings = new XmlWriterSettings { Encoding = Encoding.UTF8, CheckCharacters = false }; using (var writer = XmlWriter.Create(fileCreation.Stream, xmlSettings)) { try { fileCreation.Logger.Information("Log file - Google Merchant Center feed."); var searchContext = new ProductSearchContext { OrderBy = ProductSortingEnum.CreatedOn, PageSize = Settings.PageSize, StoreId = fileCreation.Store.Id, VisibleIndividuallyOnly = true }; var currency = Helper.GetUsedCurrency(Settings.CurrencyId); var measureWeightSystemKey = _measureService.GetMeasureWeightById(_measureSettings.BaseWeightId).SystemKeyword; writer.WriteStartDocument(); writer.WriteStartElement("rss"); writer.WriteAttributeString("version", "2.0"); writer.WriteAttributeString("xmlns", "g", null, _googleNamespace); writer.WriteStartElement("channel"); writer.WriteElementString("title", "{0} - Feed for Google Merchant Center".FormatWith(fileCreation.Store.Name)); writer.WriteElementString("link", "http://base.google.com/base/"); writer.WriteElementString("description", "Information about products"); for (int i = 0; i < 9999999; ++i) { searchContext.PageIndex = i; var products = _productService.SearchProducts(searchContext); if (fileCreation.TotalRecords == 0) { fileCreation.TotalRecords = products.TotalCount * fileCreation.StoreCount; // approx } foreach (var product in products) { fileCreation.Report(); if (product.ProductType == ProductType.SimpleProduct || product.ProductType == ProductType.BundledProduct) { WriteItem(fileCreation, writer, product, currency, measureWeightSystemKey); } else if (product.ProductType == ProductType.GroupedProduct) { var associatedSearchContext = new ProductSearchContext { OrderBy = ProductSortingEnum.CreatedOn, PageSize = int.MaxValue, StoreId = fileCreation.Store.Id, VisibleIndividuallyOnly = false, ParentGroupedProductId = product.Id }; foreach (var associatedProduct in _productService.SearchProducts(associatedSearchContext)) { WriteItem(fileCreation, writer, associatedProduct, currency, measureWeightSystemKey); } } if (taskContext.CancellationToken.IsCancellationRequested) { fileCreation.Logger.Warning("A cancellation has been requested"); break; } } if (!products.HasNextPage) { break; } } writer.WriteEndElement(); // channel writer.WriteEndElement(); // rss writer.WriteEndDocument(); if (fileCreation.ErrorMessage.HasValue()) { fileCreation.Logger.Error(fileCreation.ErrorMessage); } } catch (Exception exc) { fileCreation.Logger.Error(exc.Message, exc); } } }
public async Task Run(TaskExecutionContext ctx, CancellationToken cancelToken = default) { var count = 0; var numDeleted = 0; var numAdded = 0; var rolesCount = 0; using (var scope = new DbContextScope(_db, autoDetectChanges: false, minHookImportance: HookImportance.Important, deferCommit: true)) { // Delete existing system mappings. var deleteQuery = _db.CustomerRoleMappings.Where(x => x.IsSystemMapping); if (ctx.Parameters.ContainsKey("CustomerRoleIds")) { var roleIds = ctx.Parameters["CustomerRoleIds"].ToIntArray(); deleteQuery = deleteQuery.Where(x => roleIds.Contains(x.CustomerRoleId)); } numDeleted = await deleteQuery.BatchDeleteAsync(cancelToken); // Insert new customer role mappings. var roles = await _db.CustomerRoles .Include(x => x.RuleSets) .AsNoTracking() .Where(x => x.Active && x.RuleSets.Any(y => y.IsActive)) .ToListAsync(cancelToken); rolesCount = roles.Count; foreach (var role in roles) { var ruleSetCustomerIds = new HashSet <int>(); await ctx.SetProgressAsync(++count, roles.Count, $"Add customer assignments for role \"{role.SystemName.NaIfEmpty()}\"."); // Execute active rule sets and collect customer ids. foreach (var ruleSet in role.RuleSets.Where(x => x.IsActive)) { if (cancelToken.IsCancellationRequested) { return; } var expressionGroup = await _ruleService.CreateExpressionGroupAsync(ruleSet, _targetGroupService); if (expressionGroup is FilterExpression expression) { var filterResult = _targetGroupService.ProcessFilter(expression, 0, 500); var resultPager = new FastPager <Customer>(filterResult.SourceQuery, 500); while ((await resultPager.ReadNextPageAsync(x => x.Id, x => x)).Out(out var customerIds)) { ruleSetCustomerIds.AddRange(customerIds); } } } // Add mappings. if (ruleSetCustomerIds.Any()) { foreach (var chunk in ruleSetCustomerIds.Slice(500)) { if (cancelToken.IsCancellationRequested) { return; } foreach (var customerId in chunk) { _db.CustomerRoleMappings.Add(new CustomerRoleMapping { CustomerId = customerId, CustomerRoleId = role.Id, IsSystemMapping = true }); ++numAdded; } await scope.CommitAsync(cancelToken); } try { scope.DbContext.DetachEntities <CustomerRoleMapping>(); } catch { } } } } if (numAdded > 0 || numDeleted > 0) { await _cache.RemoveByPatternAsync(AclService.ACL_SEGMENT_PATTERN); } Debug.WriteLineIf(numDeleted > 0 || numAdded > 0, $"Deleted {numDeleted} and added {numAdded} customer assignments for {rolesCount} roles."); }
/// <summary> /// Evaluates whether this condition is valid. /// </summary> /// <param name="context">The context.</param> /// <returns> /// <c>true</c> if this instance is valid; <c>false</c> otherwise. /// </returns> public override bool Evaluate(TaskExecutionContext context) { var isValid = context.CurrentStatus == this.Value; return isValid; }
/// <summary> /// Evaluates whether this condition is valid. /// </summary> /// <param name="context">The context.</param> /// <returns> /// <c>true</c> if this instance is valid; <c>false</c> otherwise. /// </returns> public override bool Evaluate(TaskExecutionContext context) { var passed = this.Children.Any(c => c.Evaluate(context)); return(passed); }
public void StartChildStartsANewChildContext() { var writerMock = new Mock<XmlWriter>(MockBehavior.Strict); writerMock.Setup(w => w.WriteStartElement(null, "task", null)).Verifiable(); writerMock.MockWriteAttributeString("name", "TestComment"); writerMock.MockWriteAttributeString("type", "Comment"); writerMock.MockWriteElementString("start", "2010-01-01T12:01:01"); var clockMock = new Mock<IClock>(MockBehavior.Strict); clockMock.Setup(c => c.Now).Returns(new DateTime(2010, 1, 1, 12, 1, 1)); var task = new Comment("TestComment"); var context = new TaskExecutionContext( new TaskExecutionParameters { XmlWriter = writerMock.Object, Clock = clockMock.Object }); var child = context.StartChild(task); Assert.IsNotNull(child); Assert.AreSame(context, child.Parent); Assert.AreSame(context.ModificationSets, child.ModificationSets); writerMock.Verify(); }
public async Task <HttpResponseMessage> InvokeAsync(DownloadAndExecuteCommandInfo commandInfo, TaskExecutionContext context, CancellationToken cancellationToken) { DirectoryInfo tempDirectory; do { tempDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); } while (tempDirectory.Exists); var filename = Path.Combine(tempDirectory.FullName, commandInfo.FileName); var processStartInfo = commandInfo.ToStartInfo(filename); if (commandInfo.WaitForExit) { tempDirectory.Create(); try { using (var fileStream = new FileStream(filename, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite, 8192, FileOptions.DeleteOnClose)) { if (!await commandInfo.FileSource.WriteTo(fileStream, context, this)) { return(Log(HttpStatusCode.InternalServerError)); } return(await StartProcess(processStartInfo, waitForExit : true, cancellationToken)); } } finally { tempDirectory.Delete(true); } } FileHelper.RemoveOnReboot(filename); FileHelper.RemoveOnReboot(tempDirectory.FullName); tempDirectory.Create(); using (var fileStream = new FileStream(filename, FileMode.CreateNew, FileAccess.Write)) { if (!await commandInfo.FileSource.WriteTo(fileStream, context, this)) { return(Log(HttpStatusCode.InternalServerError)); } } return(await StartProcess(processStartInfo, waitForExit : false, cancellationToken)); }
public JsonResult PerformInstall(bool onlyCheck) { if (!onlyCheck) { var statuses = new List <InstallStatus>(); var context = new TaskExecutionContext(this, new TaskEventArgs(_requestContext.Application.FrameworkContext, null)); //for each hive provider, get them to serialize their config to our xml file foreach (var hive in _requestContext.Application.Hive.GetAllReadWriteProviders()) { var installStatus = hive.Bootstrapper.GetInstallStatus(); //it needs to be configured by now, if (installStatus.StatusType == InstallStatusType.Pending || installStatus.StatusType == InstallStatusType.TriedAndFailed) { var status = hive.Bootstrapper.TryInstall(); statuses.Add(status); //now check if was successful and see if there are some tasks to run if (status.StatusType == InstallStatusType.Completed) { foreach (var t in status.TasksToRun) { t.Execute(context); } } } } //TODO: Handle this ////if for some reason there's nothing been installed //if (statuses.Count == 0) //{ // if (!_requestContext.Application.AnyProvidersHaveStatus(InstallStatusType.Pending)) // { // //go back to step one // return RedirectToAction("Index"); // } //} //now, if there were no errors, then we can run the post hive install tasks if (!statuses.Any(x => x.StatusType == InstallStatusType.TriedAndFailed)) { context = _requestContext.Application.FrameworkContext.TaskManager.ExecuteInContext( TaskTriggers.Hive.PostInstall, this, new TaskEventArgs(_requestContext.Application.FrameworkContext, new EventArgs())); } if (!context.Exceptions.Any()) { return(Json(new { status = "complete", message = "Installation completed!", percentage = 100 })); } else { context.Exceptions.AddRange(statuses.Where(x => x.StatusType == InstallStatusType.TriedAndFailed).SelectMany(x => x.Errors).ToArray()); var errorMsg = ControllerContext.RenderPartialViewToString("Error", context.Exceptions); return(Json(new { status = "failure", message = errorMsg, percentage = 100, fail = true })); } } return(Json(new { percentage = 40 })); }
/// <summary> /// Executes this task. /// </summary> /// <param name="context">The context.</param> /// <returns> /// The child tasks to execute. /// </returns> protected override IEnumerable <Task> OnRun(TaskExecutionContext context) { logger.Info("Doing nothing"); return(null); }
/// <summary> /// Executes the specified process for a project item. /// </summary> /// <param name="processInfo">The process info.</param> /// <param name="item">The item.</param> /// <returns> /// The result of the execution. /// </returns> public ProcessResult Execute(ProcessInfo processInfo, ProjectItem item, TaskExecutionContext context) { var logFile = context.GeneratePathInWorkingDirectory(item.NameOrType + ".log"); return this.Execute(processInfo, item.Project.Name, item.NameOrType, logFile); }
/// <summary> /// Sends the request to a remote server. /// </summary> /// <param name="context">The context.</param> private void SendRemoteRequest(TaskExecutionContext context) { // Generate the connection var connection = this.ServerConnectionFactory.GenerateConnection(this.ServerAddress); // Resolve the URN var urn = this.ProjectName; if (!UrnHelpers.IsCCNetUrn(urn)) { urn = this.ServerConnectionFactory.GenerateUrn(this.ServerAddress, urn); } // Send the actual request logger.Debug("Sending force build on '{0}' to '{1}'", urn, this.ServerAddress); try { connection.Invoke(urn, "ForceBuild"); var message = "Force build successfully sent to '" + ProjectName + "' at '" + this.ServerAddress + "'"; logger.Info(message); context.AddEntryToBuildLog(message); } catch (RemoteServerException error) { var message = "Force build failed for '" + ProjectName + "' at '" + this.ServerAddress + "' - result code " + error.ResultCode; logger.Info(message); context.AddEntryToBuildLog(message); context.CurrentStatus = IntegrationStatus.Failure; } }
public Task Run(TaskExecutionContext ctx, CancellationToken cancelToken = default) { return(_cacheManager.ClearAsync()); }
public void Write(IDataReader source, string table, TaskExecutionContext context) { throw new NotImplementedException(); }
/// <summary> /// Runs the actions for PrePackageUninstall and for the packagefoldername specific task /// </summary> /// <param name="taskExecContext"></param> /// <param name="packageFolderName"></param> internal void RunPrePackageUninstallActions(TaskExecutionContext taskExecContext, string packageFolderName) { _backOfficeRequestContext.Application.FrameworkContext.TaskManager.ExecuteInContext(TaskTriggers.PrePackageUninstall, taskExecContext); _backOfficeRequestContext.Application.FrameworkContext.TaskManager.ExecuteInContext(packageFolderName + "-" + TaskTriggers.PrePackageUninstall, taskExecContext); }
/// <summary> /// Executes a task /// </summary> public void Execute(TaskExecutionContext ctx) { _cacheManager.Clear(); }
/// <summary> /// Sends the request to the local server. /// </summary> /// <param name="context">The context.</param> private void SendLocalRequest(TaskExecutionContext context) { // Resolve the URN var urn = this.ProjectName; if (!UrnHelpers.IsCCNetUrn(urn)) { urn = UrnHelpers.GenerateProjectUrn(this.Project.Server, this.ProjectName); } // Send the actual request logger.Debug("Performing local force build on '{0}'", urn); var arguments = new InvokeArguments { Action = "ForceBuild" }; var result = this.Project.Server.ActionInvoker.Invoke(urn, arguments); // Check the result if (result.ResultCode == RemoteResultCode.Success) { var message = "Force build successfully sent to '" + ProjectName + "'"; logger.Info(message); context.AddEntryToBuildLog(message); } else { var message = "Force build failed for '" + ProjectName + "' - result code " + result.ResultCode; logger.Info(message); context.AddEntryToBuildLog(message); context.CurrentStatus = IntegrationStatus.Failure; } }
public override async Task ExecuteAsync(TaskExecutionContext ctx) { var count = 0; var numDeleted = 0; var numAdded = 0; var numCategories = 0; var pageSize = 500; var pageIndex = -1; var categoryIds = ctx.Parameters.ContainsKey("CategoryIds") ? ctx.Parameters["CategoryIds"].ToIntArray() : null; // Hooks are enabled because search index needs to be updated. using (var scope = new DbContextScope(ctx: _productCategoryRepository.Context, autoDetectChanges: false, validateOnSave: false, hooksEnabled: true, autoCommit: false)) { // Delete existing system mappings. var deleteQuery = _productCategoryRepository.Table.Where(x => x.IsSystemMapping); if (categoryIds != null) { deleteQuery = deleteQuery.Where(x => categoryIds.Contains(x.CategoryId)); } var pager = new FastPager <ProductCategory>(deleteQuery, pageSize); while (pager.ReadNextPage(out var mappings)) { if (ctx.CancellationToken.IsCancellationRequested) { return; } if (mappings.Any()) { _productCategoryRepository.DeleteRange(mappings); numDeleted += await scope.CommitAsync(); } } try { _productCategoryRepository.Context.DetachEntities <ProductCategory>(); } catch { } // Insert new product category mappings. var categoryQuery = _categoryRepository.TableUntracked.Expand(x => x.RuleSets); if (categoryIds != null) { categoryQuery = categoryQuery.Where(x => categoryIds.Contains(x.Id)); } var categories = await categoryQuery .Where(x => x.Published && !x.Deleted && x.RuleSets.Any(y => y.IsActive)) .ToListAsync(); numCategories = categories.Count; foreach (var category in categories) { var ruleSetProductIds = new HashSet <int>(); ctx.SetProgress(++count, categories.Count, $"Add product mappings for category \"{category.Name.NaIfEmpty()}\"."); // Execute active rule sets and collect product ids. foreach (var ruleSet in category.RuleSets.Where(x => x.IsActive)) { if (ctx.CancellationToken.IsCancellationRequested) { return; } if (_ruleFactory.CreateExpressionGroup(ruleSet, _productRuleProvider) is SearchFilterExpression expression) { pageIndex = -1; while (true) { // Do not touch searchResult.Hits. We only need the product identifiers. var searchResult = _productRuleProvider.Search(new SearchFilterExpression[] { expression }, ++pageIndex, pageSize); ruleSetProductIds.AddRange(searchResult.HitsEntityIds); if (pageIndex >= (searchResult.TotalHitsCount / pageSize)) { break; } } } } // Add mappings. if (ruleSetProductIds.Any()) { foreach (var chunk in ruleSetProductIds.Slice(500)) { if (ctx.CancellationToken.IsCancellationRequested) { return; } foreach (var productId in chunk) { _productCategoryRepository.Insert(new ProductCategory { ProductId = productId, CategoryId = category.Id, IsSystemMapping = true }); ++numAdded; } await scope.CommitAsync(); } try { _productCategoryRepository.Context.DetachEntities <ProductCategory>(); } catch { } } } } Debug.WriteLineIf(numDeleted > 0 || numAdded > 0, $"Deleted {numDeleted} and added {numAdded} product mappings for {numCategories} categories."); }
public void Execute(TaskExecutionContext ctx) { var toUtc = DateTime.UtcNow.AddDays(-_commonSettings.MaxLogAgeInDays); _logService.ClearLog(toUtc, LogLevel.Error); }
/// <summary> /// Executes a task /// </summary> public void Execute(TaskExecutionContext ctx) { string weekday = DateTime.Today.DayOfWeek.ToString(); //WritetoLog("Executing roi"); var customerplans = _customerPlanService.GetAllCustomerPlans().ToList(); //WritetoLog("totalpurchase"+customerplans.Count().ToString()); foreach (var cp in customerplans) { if (cp.Customer.Active && cp.IsActive && !cp.IsExpired) { //WritetoLog("isactive"+cp.Customer.Id); var plan = _planService.GetPlanById(cp.PlanId); int PayEveryXHour = plan.PayEveryXDays; TimeSpan diff = DateTime.Now - cp.LastPaidDate; double LastPaidHours = diff.TotalHours; var vacationdate = cp.Customer.GetAttribute <DateTime>(SystemCustomerAttributeNames.VacationModeExpiryDate); var nextSurfdate = cp.Customer.GetAttribute <DateTime>(SystemCustomerAttributeNames.NextSurfDate); int NoOfAdsToSurf = 10; if (vacationdate > DateTime.Today || nextSurfdate > DateTime.Now) { NoOfAdsToSurf = 0; } NoOfAdsToSurf = 0; if (cp.AmountInvested > 0 && NoOfAdsToSurf == 0) { //WritetoLog("sharing now"); float repurchaseAmount = 0; float DailyROIToPay = 0; float HourlyROIToPay = 0; DailyROIToPay = ((cp.AmountInvested * plan.ROIPercentage) / 100); HourlyROIToPay = DailyROIToPay; // / 24; //repurchaseAmount = (HourlyROIToPay * 30) / 100; //Transaction transaction = new Transaction(); //transaction.CustomerId = cp.CustomerId; //transaction.Amount = HourlyROIToPay; //transaction.FinalAmount = transaction.Amount; //transaction.RefId = cp.Id; //transaction.StatusId = (int)Status.Completed; //transaction.TransactionDate = DateTime.Now; //transaction.TranscationTypeId = (int)TransactionType.ROI; //_transactionService.InsertTransaction(transaction); //WritetoLog("sharing now1"+ transaction.Amount); //transaction = new Transaction(); //transaction.CustomerId = cp.CustomerId; //transaction.Amount = repurchaseAmount; //transaction.FinalAmount = transaction.Amount; //transaction.RefId = cp.Id; //transaction.StatusId = (int)Status.Completed; //transaction.TransactionDate = DateTime.Now; //transaction.TranscationTypeId = (int)TransactionType.RepurchaseROI; //_transactionService.InsertTransaction(transaction); //Update CustomerPlan cp.LastPaidDate = DateTime.Now; cp.ROIPaid = cp.ROIPaid + HourlyROIToPay; //cp.RepurchaseWallet = cp.RepurchaseWallet + repurchaseAmount; cp.NoOfPayoutPaid = cp.NoOfPayoutPaid + 1; if (cp.ROIPaid >= cp.ROIToPay) { cp.ExpiredDate = DateTime.Now; cp.IsExpired = true; cp.IsActive = false; //if (plan.IsPrincipalBack) //{ // //Retrun Principal // transaction = new Transaction(); // transaction.CustomerId = cp.CustomerId; // transaction.Amount = cp.AmountInvested; // transaction.FinalAmount = transaction.Amount; // transaction.RefId = cp.Id; // transaction.StatusId = (int)Status.Completed; // transaction.TransactionDate = DateTime.Now; // transaction.TranscationTypeId = (int)TransactionType.ROI; // _transactionService.InsertTransaction(transaction); //} } _customerPlanService.UpdateCustomerPlan(cp); } } } }
/// <summary> /// Executes this task. /// </summary> /// <param name="context">The context.</param> /// <returns> /// The child tasks to execute. /// </returns> protected override IEnumerable<Task> OnRun(TaskExecutionContext context) { throw new NotImplementedException(); }
public async Task <HttpResponseMessage> InvokeAsync(ServerTestCommandInfo commandInfo, TargetId targetId, TaskExecutionContext context, CancellationToken cancellationToken) { for (int i = 0; i < 100; i++) { await Task.Delay(100, cancellationToken); context.ReportProgress(i / 100d); context.ReportStatus($"Doing some stuff ({i}%)"); } return(new HttpResponseMessage(HttpStatusCode.OK)); }