public void Should_invoke_a_command_with_flags() { var commandResult = new CommandResult { MatchResults = new List<IMatchResult> { new MatchResult() }, OptionalMatchResults = new List<IMatchResult> { new NamedValueMatchResult("option", "value") } }; dynamic parameterResults = null; dynamic flagResults = null; var command = new Command("command [-o|option]", (parameters, flags) => { parameterResults = parameters; flagResults = flags; }); var commandInvoker = new DefaultCommandInvoker(); commandInvoker.Invoke(commandResult, command); Assert.NotNull(parameterResults); Assert.Empty((ExpandoObject)parameterResults); Assert.NotNull(flagResults); Assert.Equal(1, ((ExpandoObject)flagResults).Count()); Assert.Equal("value", flagResults.option); }
public static ModelStateDictionary AddModelErrors(this ModelStateDictionary modelState, CommandResult result) { foreach (var error in result.Errors) modelState.AddModelError(error.Key, error.Error); return modelState; }
public void Result_should_wire_the_success_and_failure_results() { var result = new CommandResult<Message, Entity>(new Message(), entity => new ViewResult {ViewName = "foo"}, message => new ViewResult {ViewName = "bar"}); result.Success.AssertViewRendered().ForView("foo"); result.Failure.AssertViewRendered().ForView("bar"); }
public override CommandResult Execute(CommandTreeViewNode node = null) { CommandResult rlt = new CommandResult(); try { object resultValue = new CommandResult(); if (string.Equals(CommandExecutionContext.Instance.CurrentMachine.Address, ".") || string.Equals(CommandExecutionContext.Instance.CurrentMachine.Address, "127.0.0.1")) { ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "cmd.exe"; info.Arguments = string.Format("/c {0}", this.Command_Line); Process.Start(info); } else { resultValue = RemoteExecute(this.Command_Line); } rlt.ResultValue = resultValue; } catch (Exception e) { rlt.LastError = e; } return rlt; }
private CommandResult ExecuteInternal() { CommandResult result = new CommandResult(); if (Is_Running) { while (!isCancelling) { using (ServiceController sc = new ServiceController(Service_Name, CommandExecutionContext.Instance.CurrentMachine.Address)) { if (sc.Status == ServiceControllerStatus.Running) { break; } } Thread.Sleep(Interval); } } else { while (!isCancelling) { using (ServiceController sc = new ServiceController(Service_Name, CommandExecutionContext.Instance.CurrentMachine.Address)) { if (sc.Status == ServiceControllerStatus.Stopped) { break; } } Thread.Sleep(Interval); } } base.AccomplishCancellation(); return result; }
public void Saml2RedirectBinding_Bind() { // Example from http://en.wikipedia.org/wiki/SAML_2.0#HTTP_Redirect_Binding var xmlData = @"<?xml version=""1.0"" encoding=""UTF-8""?> <samlp:AuthnRequest xmlns:samlp=""urn:oasis:names:tc:SAML:2.0:protocol"" xmlns:saml=""urn:oasis:names:tc:SAML:2.0:assertion"" ID=""aaf23196-1773-2113-474a-fe114412ab72"" Version=""2.0"" IssueInstant=""2004-12-05T09:21:59Z"" AssertionConsumerServiceIndex=""0"" AttributeConsumingServiceIndex=""0""> <saml:Issuer>https://sp.example.com/SAML2</saml:Issuer> <samlp:NameIDPolicy AllowCreate=""true"" Format=""urn:oasis:names:tc:SAML:2.0:nameid-format:transient""/> </samlp:AuthnRequest> "; var serializedData = "fZFfa8IwFMXfBb9DyXvaJtZ1BqsURRC2Mabbw95ivc5Am3TJrXPffmmLY3%2fA15Pzuyf33On8XJXBCaxTRmeEhTEJQBdmr%2fRbRp63K3pL5rPhYOpkVdYib%2fCon%2bC9AYfDQRB4WDvRvWWksVoY6ZQTWlbgBBZik9%2ffCR7GorYGTWFK8pu6DknnwKL%2fWEetlxmR8sBHbHJDWZqOKGdsRJM0kfQAjCUJ43KX8s78ctnIz%2blp5xpYa4dSo1fjOKGM03i8jSeCMzGevHa2%2fBK5MNo1FdgN2JMqPLmHc0b6WTmiVbsGoTf5qv66Zq2t60x0wXZ2RKydiCJXh3CWVV1CWJgqanfl0%2bin8xutxYOvZL18NKUqPlvZR5el%2bVhYkAgZQdsA6fWVsZXE63W2itrTQ2cVaKV2CjSSqL1v9P%2fAXv4C"; // hand patched with lower case version of UrlEncode characters to match the .NET UrlDecode output var destinationUri = new Uri("http://www.example.com/acs"); var subject = Saml2Binding.Get(Saml2BindingType.HttpRedirect).Bind(xmlData, destinationUri, null); var expected = new CommandResult() { Location = new Uri("http://www.example.com/acs?SAMLRequest=" + serializedData), HttpStatusCode = System.Net.HttpStatusCode.SeeOther, }; subject.ShouldBeEquivalentTo(expected); }
public override void Run(CommandResult rlt, bool isPreview = false) { tfsroot = Executor.Instance.ParseIdString(TfsRoot); srcbranch = Executor.Instance.ParseIdString(SrcBranch); desbranch = Executor.Instance.ParseIdString(DesBranch); tool = Executor.Instance.ParseIdString(Tool); AppendSymbol(ref tfsroot); foreach (string i in SrcFiles) { string src = i; if (src.StartsWith("###")) { src = src.Replace("###", tfsroot); } else if (src.StartsWith("$/Root") || src.StartsWith("$\\Root")) { src = src.Replace("$/Root", tfsroot); src = src.Replace("$\\Root", tfsroot); src = src.Replace("/", "\\"); src = src.Replace("\\\\", "\\"); } if (!src.EndsWith("\\")) { Compare(src); } else { string[] files = Directory.GetFiles(src, "*.*", SearchOption.AllDirectories); foreach (string file in files) { Compare(file); } } } }
public CommandResult RunCommand(string command) { CommandResult result = new CommandResult(); MemoryStream ms = new MemoryStream(); try { m_pythonEngine.Runtime.IO.SetOutput(ms, new StreamWriter(ms, Encoding.UTF8)); object o = m_pythonEngine.Execute(command, m_scriptScope); result.output = ReadStream(ms); if (o != null) { result.returnValue = o; m_scriptScope.SetVariable("_", o); try { string objectStr = m_pythonEngine.Execute("repr(_)", m_scriptScope).ToString(); result.returnValueStr = objectStr; } catch { result.returnValueStr = o.ToString(); } } } catch (System.Exception e) { result.output = ReadStream(ms); result.exception = e; } ms.Dispose(); return result; }
public CommandResult RunAndWaitForExit() { CommandResult result = new CommandResult(); using (Process process = Process.Start(CreateStartInfo(_command, _args))) { if (!string.IsNullOrEmpty(_input)) { using (StreamWriter inputWriter = process.StandardInput) { inputWriter.Write(_input); } } process.WaitForExit(); result.ExitCode = process.ExitCode; using (StreamReader outputReader = process.StandardOutput) { result.Output = outputReader.ReadToEnd(); } using (StreamReader errorReader = process.StandardError) { result.Error = errorReader.ReadToEnd(); } return result; } }
public override void Run(CommandResult rlt, bool isPreview = false) { if (!IsBypass) { Process.Start(Executor.Instance.ParseIdString(Cmd), Executor.Instance.ParseIdString(Args)); } }
public override CommandResult Execute(CommandTreeViewNode node = null) { CommandResult result = new CommandResult(); CommandExecutionContext.Instance.CurrentMachine.DomainUsername = Username; CommandExecutionContext.Instance.CurrentMachine.Password = Password; CommandExecutionContext.Instance.CurrentMachine.Address = Address; return result; }
public void RaiseCommandRan(CommandRunData data, CommandResult result) { var e = CommandRan; if (e != null) { e(this, Tuple.Create(data, result)); } }
public override void Run(CommandResult rlt, bool isPreview = false) { ConnectCommand cn = Executor.Instance.Get<ConnectCommand>(ConnectionId); ImpersonateUser iu = new ImpersonateUser(); iu.Impersonate(cn.Domain, cn.User, cn.Pwd); ExecuteInternal(cn); iu.Undo(); }
protected void AssertInsertWithTransaction(CommandResult result) { Assert.True(result.IsCompleted); var modeSwitch = result.AsCompleted().Item; Assert.True(modeSwitch.IsSwitchModeWithArgument); var data = modeSwitch.AsSwitchModeWithArgument(); Assert.Equal(ModeKind.Insert, data.Item1); Assert.True(data.Item2.IsInsertWithTransaction); }
public static Exception GetError(XName commandName, CommandResult result, SqlDataReader reader) { Exception returnValue = null; if (result != CommandResult.Success) { switch (result) { case CommandResult.InstanceAlreadyExists: returnValue = new InstanceCollisionException(commandName, reader.GetGuid(1)); break; case CommandResult.InstanceLockNotAcquired: returnValue = new InstanceLockedException(commandName, reader.GetGuid(1), reader.GetGuid(2), ReadLockOwnerMetadata(reader)); break; case CommandResult.InstanceNotFound: returnValue = new InstanceNotReadyException(commandName, reader.GetGuid(1)); break; case CommandResult.KeyAlreadyExists: returnValue = new InstanceKeyCollisionException(commandName, Guid.Empty, new InstanceKey(reader.GetGuid(1)), Guid.Empty); break; case CommandResult.KeyNotFound: returnValue = new InstanceKeyNotReadyException(commandName, new InstanceKey(reader.GetGuid(1))); break; case CommandResult.InstanceLockLost: returnValue = new InstanceLockLostException(commandName, reader.GetGuid(1)); break; case CommandResult.InstanceCompleted: returnValue = new InstanceCompleteException(commandName, reader.GetGuid(1)); break; case CommandResult.KeyDisassociated: returnValue = new InstanceKeyCompleteException(commandName, new InstanceKey(reader.GetGuid(1))); break; case CommandResult.StaleInstanceVersion: returnValue = new InstanceLockLostException(commandName, reader.GetGuid(1)); break; case CommandResult.HostLockExpired: returnValue = new InstancePersistenceException(SR.HostLockExpired); break; case CommandResult.HostLockNotFound: returnValue = new InstancePersistenceException(SR.HostLockNotFound); break; case CommandResult.CleanupInProgress: returnValue = new InstancePersistenceCommandException(SR.CleanupInProgress); break; case CommandResult.InstanceAlreadyLockedToOwner: returnValue = new InstanceAlreadyLockedToOwnerException(commandName, reader.GetGuid(1), reader.GetInt64(2)); break; default: returnValue = new InstancePersistenceCommandException(SR.UnknownSprocResult(result)); break; } } return returnValue; }
public override void Run(CommandResult rlt, bool isPreview = false) { if (Condition == null) { rlt.BoolResult = IsNot ? true : false; } else { rlt.BoolResult = IsNot ? !Condition.IsTrue : Condition.IsTrue; } }
public void CommandResultExtensions_ToActionResult_UknownStatusCode() { var cr = new CommandResult() { HttpStatusCode = System.Net.HttpStatusCode.SwitchingProtocols }; Action a = () => cr.ToActionResult(); a.ShouldThrow<NotImplementedException>(); }
public static CommandResult PrepareRequestAndExecute(Command command, string privateKey, CommandResult.JsonPreparer<Command, CommandResult> baseExecutor) { var sb = new StringBuilder(); foreach ( var parameter in command.Parameters) if (String.CompareOrdinal(parameter.Key, @"userapp") != 0) sb.Append(parameter.Value); sb.Append(privateKey ?? ""); return baseExecutor(command.WithParameter("sum", StringUtils.Md5(sb.ToString()))); }
public CommandResult Validate(object instance) { var validationResults = new List<ValidationResult>(); Validator.TryValidateObject(instance, new ValidationContext(instance), validationResults, true); var serviceResult = new CommandResult(); foreach (var validationResult in validationResults) serviceResult.Add(validationResult.MemberNames.Join(", "), validationResult.ErrorMessage); return serviceResult; }
public override void Run(CommandResult rlt, bool isPreview=false) { if (!string.IsNullOrEmpty(Id)) { if (!IsReference) { Executor.Instance.SetVar(Id, IsCondition, this.Clone()); } else { Executor.Instance.SetVar(Id, IsCondition, this); } } if (!string.IsNullOrEmpty(ContentId)) { string targetId = TargetId; if (string.IsNullOrEmpty(targetId)) { targetId = this.Id; } if (!string.IsNullOrEmpty(targetId)) { object o = Executor.Instance.GetObject(ContentId); if (o is string) { string s = (string)o; Executor.Instance.SetVar(targetId, IsCondition, s); } else if (o is CommandNode) { CommandNode c = (CommandNode)o; if (c != null) { c.Visible = false; if (!IsReference) { CommandNode cloned = c.Clone(); cloned.Id = null; cloned.Visible = this.Visible; Executor.Instance.SetVar(TargetId, IsCondition, cloned); } else { c.Visible = Visible; Executor.Instance.SetVar(TargetId, IsCondition, c); } } } } } }
public void CommandResultExtensions_ToActionResult_SeeOther() { var cr = new CommandResult() { HttpStatusCode = System.Net.HttpStatusCode.SeeOther, Location = new Uri("http://example.com/location") }; var subject = cr.ToActionResult(); subject.Should().BeOfType<RedirectResult>().And .Subject.As<RedirectResult>().Url.Should().Be("http://example.com/location"); }
public static CommandResult<Person> Add(Person p) { var result = new CommandResult<Person> { Entity = p }; result.Messages.AddRange(Validate(p)); if (result.Successful) { return result; } p.ID = People.Count + 1; People.Add(p); return result; }
public void Intercept(IInvocation invocation) { try { invocation.Proceed(); } catch(Exception ex) { ex = Unwrap(ex); var result = new CommandResult {Status = CommandStatus.Failed, Message = ex.Message}; invocation.ReturnValue = result; } }
protected override void DoExecute(CommandResult<ListCommandResult> result) { base.DoExecute(result); foreach (var instance in result.Data.Instances) { if (File.Exists(instance)) { continue; } File.Create(instance).Close(); } }
public override void Run(CommandResult rlt, bool isPreview=false) { string targetId = null, outputId = null; if (!string.IsNullOrEmpty(TargetId)) { targetId = Executor.Instance.ParseIdString(TargetId); outputId = targetId; } if (!string.IsNullOrEmpty(OutputId)) { outputId = Executor.Instance.ParseIdString(OutputId); } if (!string.IsNullOrEmpty(targetId)) { DataSet ds = Executor.Instance.Get<DataSet>(targetId); if (IsReadMode && ds == null && !string.IsNullOrEmpty(Filename)) { string filename = Filename.PathMakeAbsolute(); string content = File.ReadAllText(filename); ds = content.FromXml<DataSet>(); } if (ds != null && IsText && ds.Tables.Count > 0) { BackupDataset(ds); DataTable table = ds.Tables[0]; List<string> sqls = new List<string>(); foreach (DataRow row in table.Rows) { object data = GetCellData(row); if (data != null) { sqls.Add(data.ToString()); } } //Executor.Instance.SetVar(outputId, false, string.Join("\r\n", sqls.ToArray())); rlt.IsCondition = false; rlt.ResultValue = string.Join("\r\n", sqls.ToArray()); } else { rlt.LastError = new Exception(string.Format("Cannot parse null DataSet of id {0}. Please check whether the ExecuteSql task (which has the same ResultId) has generated correct output.", targetId)); } } else { rlt.LastError = new ArgumentNullException("TargetId cannot be null"); } }
private void ExecuteSql(CommandResult rlt) { try { SqlConnection conn = GetConnection(ConnectionId, Database); if (conn != null) { if (string.IsNullOrEmpty(Sql) && string.IsNullOrEmpty(SqlId)) { if (File.Exists(SqlFile)) { FileInfo file = new FileInfo(SqlFile); string script = file.OpenText().ReadToEnd(); ServerConnection sconn = new ServerConnection(conn); Server server = new Server(sconn); Logger.Log2File("-----------------------------------------------------------------------------------"); Logger.Log2File(string.Format("-- Preparing to execute file sql:\r\n{0}", script)); if (string.IsNullOrEmpty(ResultId) && string.IsNullOrEmpty(OutputId)) { server.ConnectionContext.ExecuteNonQuery(script); } else { DataSet ds = server.ConnectionContext.ExecuteWithResults(script); SaveResult(rlt, ds); } } else { rlt.LastError = new FileNotFoundException(); } } else { string sql = Executor.Instance.ParseIdString(Sql); if (!string.IsNullOrEmpty(SqlId)) { sql = Executor.Instance.GetString(SqlId); } DataSet ds = ExecuteSql(ConnectionId, Database, sql, !string.IsNullOrEmpty(ResultId) || !string.IsNullOrEmpty(OutputId)); SaveResult(rlt, ds); } } } catch (Exception e) { rlt.LastError = e; } }
protected override void NotifyCommandResult(int commandId, string status, string result) { try { TaskCompletionSource<CommandResult> cr = _cmdData[commandId]; CommandResult rv = new CommandResult() { Result = result, Status = status }; cr.SetResult(rv); } catch (Exception ) { } // if a command with unknown id comes in - we aren't interested in it }
public override void Run(CommandResult rlt, bool isPreview = false) { try { string path = Executor.Instance.ParseIdString(Path); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } catch (Exception e) { rlt.LastError = e; } }
public void CommandResultExtensions_ToActionResult_Ok() { var cr = new CommandResult() { Content = "Some Content!", ContentType = "application/whatever+text" }; var subject = cr.ToActionResult(); subject.Should().BeOfType<ContentResult>().And .Subject.As<ContentResult>().Content.Should().Be(cr.Content); subject.As<ContentResult>().ContentType.Should().Contain(cr.ContentType); }
public override void Run(CommandResult rlt, bool isPreview = false) { string jobname = Executor.Instance.ParseIdString(JobName); string[] jobs = jobname.Split(';'); foreach (string i in jobs) { CommandResult r = RunJob(Executor.Instance.ParseIdString(i)); if (r.LastError != null && rlt.LastError == null) { rlt.LastError = r.LastError; rlt.ConfirmExecution = rlt.ConfirmExecution || r.ConfirmExecution; Logger.Log(r.LastError.ToString()); } } }
private Task CompleteCommand(ProcessingCommand processingCommand, CommandStatus commandStatus, string resultType, string result) { var commandResult = new CommandResult(commandStatus, processingCommand.Message.Id, processingCommand.Message.AggregateRootId, result, resultType); return(processingCommand.MailBox.CompleteMessage(processingCommand, commandResult)); }
public async Task <ICommandResult <Article> > SendAsync(INotificationContext <Article> context) { // Validate if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.Notification == null) { throw new ArgumentNullException(nameof(context.Notification)); } if (context.Notification.Type == null) { throw new ArgumentNullException(nameof(context.Notification.Type)); } if (context.Notification.To == null) { throw new ArgumentNullException(nameof(context.Notification.To)); } // Ensure correct notification provider if (!context.Notification.Type.Name.Equals(WebNotifications.ArticleSpam.Name, StringComparison.Ordinal)) { return(null); } // Create result var result = new CommandResult <Article>(); var baseUri = await _urlHelper.GetBaseUrlAsync(); var url = _urlHelper.GetRouteUrl(baseUri, new RouteValueDictionary() { ["area"] = "Plato.Articles", ["controller"] = "Home", ["action"] = "Display", ["opts.id"] = context.Model.Id, ["opts.alias"] = context.Model.Alias }); //// Build notification var userNotification = new UserNotification() { NotificationName = context.Notification.Type.Name, UserId = context.Notification.To.Id, Title = S["Possible SPAM"].Value, Message = S["An article has been detected as SPAM!"], Url = url, CreatedUserId = context.Notification.From?.Id ?? 0, CreatedDate = DateTimeOffset.UtcNow }; // Create notification var userNotificationResult = await _userNotificationManager.CreateAsync(userNotification); if (userNotificationResult.Succeeded) { return(result.Success(context.Model)); } return(result.Failed(userNotificationResult.Errors?.ToArray())); }
protected override bool DeletingItem(object item) { CommandResult ret = (new OTTypeBLL(AppSettings.CurrentSetting.ConnectUri)).Delete(item as OTType); return(ret.Result == ResultCode.Successful); }
public CommandResult Execute(Command command, CommandMeta meta, ICommandSyntax syntax) { return(CommandResult.AsSucceed("Карточка")); }
public override void OnExecute(ICommandContext context, CommandConfig config, CommandResult result) { var importResult = result as ExcelImportResult; //TODO:取文件,不考虑多个文件情况 //TODO:存文件到上传临时文件夹 ~/tempfiles,考虑到文件可能重名,保存文件名应该唯一(可以用GUID) string fileName = ""; fileName.ImportExcel(Config, importResult); }
public static CommandResultAssertions Should(this CommandResult commandResult) { return(new CommandResultAssertions(commandResult)); }
public override ActionResult OnSuccessfulExecution(LoginViewModel viewModel, CommandResult commandResult) { return(RedirectToAction("Index", "Home")); }
public async Task <ICommandResult <IdeaComment> > SendAsync(INotificationContext <IdeaComment> context) { // Validate if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.Notification == null) { throw new ArgumentNullException(nameof(context.Notification)); } if (context.Notification.Type == null) { throw new ArgumentNullException(nameof(context.Notification.Type)); } if (context.Notification.To == null) { throw new ArgumentNullException(nameof(context.Notification.To)); } // Ensure correct notification provider if (!context.Notification.Type.Name.Equals(WebNotifications.CommentSpam.Name, StringComparison.Ordinal)) { return(null); } // Create result var result = new CommandResult <IdeaComment>(); // Get entity for reply var entity = await _entityStore.GetByIdAsync(context.Model.EntityId); // Ensure we found the entity if (entity == null) { return(result.Failed( $"No entity with id '{context.Model.EntityId}' exists. Failed to send reply spam web notification.")); } var baseUri = await _urlHelper.GetBaseUrlAsync(); var url = _urlHelper.GetRouteUrl(baseUri, new RouteValueDictionary() { ["area"] = "Plato.Ideas", ["controller"] = "Home", ["action"] = "Reply", ["opts.id"] = entity.Id, ["opts.alias"] = entity.Alias, ["opts.replyId"] = context.Model.Id }); //// Build notification var userNotification = new UserNotification() { NotificationName = context.Notification.Type.Name, UserId = context.Notification.To.Id, Title = S["Possible SPAM"].Value, Message = S["A doc comment has been detected as SPAM!"], Url = url, CreatedUserId = context.Notification.From?.Id ?? 0, CreatedDate = DateTimeOffset.UtcNow }; // Create notification var userNotificationResult = await _userNotificationManager.CreateAsync(userNotification); if (userNotificationResult.Succeeded) { return(result.Success(context.Model)); } return(result.Failed(userNotificationResult.Errors?.ToArray())); }
public async Task <ICommandResult <DocComment> > SendAsync(INotificationContext <DocComment> context) { // Ensure correct notification provider if (!context.Notification.Type.Name.Equals(EmailNotifications.EntityReply.Name, StringComparison.Ordinal)) { return(null); } // Create result var result = new CommandResult <DocComment>(); // Get the entity for the reply var entity = await _entityStore.GetByIdAsync(context.Model.EntityId); if (entity == null) { return(result.Failed($"No entity could be found with the Id of {context.Model.EntityId} when sending the follow notification '{EmailNotifications.EntityReply.Name}'.")); } // Get email template const string templateId = "NewDocComment"; // Tasks run in a background thread and don't have access to HttpContext // Create a dummy principal to represent the user so we can still obtain // the current culture for the email var principal = await _claimsPrincipalFactory.CreateAsync((User)context.Notification.To); var culture = await _contextFacade.GetCurrentCultureAsync(principal.Identity); var email = await _localeStore.GetFirstOrDefaultByKeyAsync <LocaleEmail>(culture, templateId); if (email != null) { // Build entity url var baseUri = await _capturedRouterUrlHelper.GetBaseUrlAsync(); var url = _capturedRouterUrlHelper.GetRouteUrl(baseUri, new RouteValueDictionary() { ["area"] = "Plato.Docs", ["controller"] = "Home", ["action"] = "Reply", ["opts.id"] = entity.Id, ["opts.alias"] = entity.Alias, ["opts.replyId"] = context.Model.Id }); // Build message from template var message = email.BuildMailMessage(); message.Body = string.Format( email.Message, context.Notification.To.DisplayName, entity.Title, baseUri + url); message.IsBodyHtml = true; message.To.Add(new MailAddress(context.Notification.To.Email)); // Send message var emailResult = await _emailManager.SaveAsync(message); if (emailResult.Succeeded) { return(result.Success(context.Model)); } return(result.Failed(emailResult.Errors?.ToArray())); } return(result.Failed($"No email template with the Id '{templateId}' exists within the 'locales/{culture}/emails.json' file!")); }
public override void OnExecute(ICommandContext context, CommandConfig config, CommandResult result) { throw new Exception("测试命令,不能执行"); }
public override async Task <CommandResult> Execute() { var activeSessions = await this.loginSessionDataService.GetAllActiveSessions(); return(CommandResult.CreateSuccessResult(activeSessions)); }
internal static CommandBinding CreateNormalBinding(string name) { return(CreateNormalBinding(name, () => CommandResult.NewCompleted(ModeSwitch.NoSwitch))); }
public override CommandResult Execute(CommandEventArgs commandEventArgs) { try { base.Execute(commandEventArgs); } catch (CommandException ex) { return(ex.CommandResult); } var entity = commandEventArgs.Entity; var basePools = entity.BaseMaxPools; var baseAttributes = entity.BaseAttributes; var baseQualities = entity.BaseQualities; var modPools = entity.ModifiedPools; var modAttributes = entity.ModifiedAttributes; var modQualities = entity.ModifiedQualities; var poolsTable = Formatter.ToTable(2, Formatter.DefaultIndent, // HP row Formatter.NewRow( "Hit Points: ", $"{entity.CurrentHitPoints}", "/", $"{basePools.HitPoints}", "" ), // Stamina row Formatter.NewRow( "Stamina: ", $"{entity.CurrentStamina}", "/", $"{basePools.Stamina}", "" ), // Energy row Formatter.NewRow( "Energy: ", $"{entity.CurrentEnergy}", "/", $"{basePools.Energy}", "" ) ); var attributesTable = Formatter.ToTable(2, Formatter.DefaultIndent, // Essence row Formatter.NewRow( "Essence: ", $"{baseAttributes.Essence}", $"[{modAttributes.Essence}]" ), // Finesse row Formatter.NewRow( "Finesse: ", $"{baseAttributes.Finesse}", $"[{modAttributes.Finesse}]" ), // Intellect row Formatter.NewRow( "Intellect: ", $"{baseAttributes.Intellect}", $"[{modAttributes.Intellect}]" ), // Might row Formatter.NewRow( "Might: ", $"{baseAttributes.Might}", $"[{modAttributes.Might}]" ), // Spirit row Formatter.NewRow( "Spirit: ", $"{baseAttributes.Spirit}", $"[{modAttributes.Spirit}]" ), // Will row Formatter.NewRow( "Will: ", $"{baseAttributes.Will}", $"[{modAttributes.Will}]" ) ); var qualitiesTable = Formatter.ToTable(2, Formatter.DefaultIndent, // Attack and Armor row Formatter.NewRow( "Attack Rating: ", $"{baseQualities.AttackRating}", $"[{modQualities.AttackRating}]", "Armor Rating: ", $"{baseQualities.ArmorRating}", $"[{modQualities.ArmorRating}]" ), // Critical Hit and Damage row Formatter.NewRow( "Critical Hit: ", $"{baseQualities.CriticalHit}", $"[{modQualities.CriticalHit}]", "Critical Damage: ", $"{baseQualities.CriticalDamage}", $"[{modQualities.CriticalDamage}]" ) ); var output = new OutputBuilder( "Statistics:\n" + poolsTable + "\n\n" + attributesTable + "\n\n" + qualitiesTable + "\n\n" ); if (entity.Currency.HasAnyValue()) { output.Append("[Currency] " + entity.Currency.ToString() + "\n\n"); } else { output.Append("[Currency] none\n\n"); } return(CommandResult.Success(output.Output)); }
protected override async Task <CommandResult> ExecuteImplementation() { return(CommandResult.Success(new JObject { "date-time", DateTime.Now })); }
public async Task post_edit() { var mockMediator = MockingKernel.GetMock <IMediator>(); mockMediator.Setup(m => m.SendAsync(It.IsAny <AddOrEditPersonCommand>())).ReturnsAsync(CommandResult.Success()); mockMediator.Setup(m => m.SendAsync(It.IsAny <UpdateUserCommand>())).ReturnsAsync(CommandResult.Success()); var model = new PersonModel { Id = TestConstants.IdA, }; var result = await Target.Edit(model.Id, new PersonEditViewModel() { Person = model }, null); result.Should().BeHttpStatusResult(HttpStatusCode.Accepted); mockMediator.Verify(m => m.SendAsync(It.Is <AddOrEditPersonCommand>(c => c.Person == model))); }
internal static int ProcessArgs(string[] args, ITelemetry telemetryClient = null) { // CommandLineApplication is a bit restrictive, so we parse things ourselves here. Individual apps should use CLA. var success = true; var command = string.Empty; var lastArg = 0; var cliFallbackFolderPathCalculator = new CliFolderPathCalculator(); TopLevelCommandParserResult topLevelCommandParserResult = TopLevelCommandParserResult.Empty; using (INuGetCacheSentinel nugetCacheSentinel = new NuGetCacheSentinel(cliFallbackFolderPathCalculator)) using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel = new FirstTimeUseNoticeSentinel(cliFallbackFolderPathCalculator)) { IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = disposableFirstTimeUseNoticeSentinel; for (; lastArg < args.Length; lastArg++) { if (IsArg(args[lastArg], "d", "diagnostics")) { Environment.SetEnvironmentVariable(CommandContext.Variables.Verbose, bool.TrueString); CommandContext.SetVerbose(true); } else if (IsArg(args[lastArg], "version")) { PrintVersion(); return(0); } else if (IsArg(args[lastArg], "info")) { PrintInfo(); return(0); } else if (IsArg(args[lastArg], "h", "help") || args[lastArg] == "-?" || args[lastArg] == "/?") { HelpCommand.PrintHelp(); return(0); } else if (args[lastArg].StartsWith("-", StringComparison.OrdinalIgnoreCase)) { Reporter.Error.WriteLine($"Unknown option: {args[lastArg]}"); success = false; } else { // It's the command, and we're done! command = args[lastArg]; if (string.IsNullOrEmpty(command)) { command = "help"; } topLevelCommandParserResult = new TopLevelCommandParserResult(command); var hasSuperUserAccess = false; if (IsDotnetBeingInvokedFromNativeInstaller(topLevelCommandParserResult)) { firstTimeUseNoticeSentinel = new NoOpFirstTimeUseNoticeSentinel(); hasSuperUserAccess = true; } ConfigureDotNetForFirstTimeUse( nugetCacheSentinel, firstTimeUseNoticeSentinel, cliFallbackFolderPathCalculator, hasSuperUserAccess); break; } } if (!success) { HelpCommand.PrintHelp(); return(1); } if (telemetryClient == null) { telemetryClient = new Telemetry.Telemetry(firstTimeUseNoticeSentinel); } TelemetryEventEntry.Subscribe(telemetryClient.TrackEvent); TelemetryEventEntry.TelemetryFilter = new TelemetryFilter(Sha256Hasher.HashWithNormalizedCasing); } IEnumerable <string> appArgs = (lastArg + 1) >= args.Length ? Enumerable.Empty <string>() : args.Skip(lastArg + 1).ToArray(); if (CommandContext.IsVerbose()) { Console.WriteLine($"Telemetry is: {(telemetryClient.Enabled ? "Enabled" : "Disabled")}"); } TelemetryEventEntry.SendFiltered(topLevelCommandParserResult); int exitCode; if (BuiltInCommandsCatalog.Commands.TryGetValue(topLevelCommandParserResult.Command, out var builtIn)) { var parseResult = Parser.Instance.ParseFrom($"dotnet {topLevelCommandParserResult.Command}", appArgs.ToArray()); if (!parseResult.Errors.Any()) { TelemetryEventEntry.SendFiltered(parseResult); } exitCode = builtIn.Command(appArgs.ToArray()); } else { CommandResult result = Command.Create( "dotnet-" + topLevelCommandParserResult.Command, appArgs, FrameworkConstants.CommonFrameworks.NetStandardApp15) .Execute(); exitCode = result.ExitCode; } return(exitCode); }
public async Task <CommandResult <string> > GetHealthAsync(CancellationToken cancellationToken) { var result = await _moduleImpl.HealthCheckAsync(); return(CommandResult <string> .Ok(result)); }
public ActionResult UpdateDataRight(string idschecks, string idsunchecks, string idsArea, string idsunArea, string idsLayerchecks, string idsLayerunchecks, string RoleId) { int _roleid = 0; if (!string.IsNullOrEmpty(RoleId)) { int.TryParse(RoleId, out _roleid); } LoginInfo lu = LoginUser; List <SqlParameter> _params = new List <SqlParameter>(); { SqlParameter p = new SqlParameter() { ParameterName = "opuser", Value = lu.User.UserName }; _params.Add(p); } { SqlParameter p = new SqlParameter() { ParameterName = "idsclass", Value = idschecks }; _params.Add(p); } { SqlParameter p = new SqlParameter() { ParameterName = "idsunClass", Value = idsunchecks }; _params.Add(p); } { SqlParameter p = new SqlParameter() { ParameterName = "idsArea", Value = idsArea }; _params.Add(p); } { SqlParameter p = new SqlParameter() { ParameterName = "idsunArea", Value = idsunArea }; _params.Add(p); } { SqlParameter p = new SqlParameter() { ParameterName = "idsLayerchecks", Value = idsLayerchecks }; _params.Add(p); } { SqlParameter p = new SqlParameter() { ParameterName = "idsLayerunchecks", Value = idsLayerunchecks }; _params.Add(p); } { SqlParameter p = new SqlParameter() { ParameterName = "proleid", Value = _roleid }; _params.Add(p); } DataProvider dp = DataProvider.GetEAP_Provider(); List <CommandResult> cr = dp.LoadData <CommandResult>("usp_SaveroleData", _params.ToArray()); // if (!((string.IsNullOrEmpty(model.RoleID) || string.IsNullOrEmpty(model.Id))) CommandResult m = new CommandResult() { IntResult = 0 }; if (cr != null && cr.Count > 0) { return(Json(cr[0])); } else { return(Json(m)); } // return sysRightBLL.UpdateRight(model); }
public async Task <ICommandResult <ReportSubmission <Doc> > > SendAsync(INotificationContext <ReportSubmission <Doc> > context) { // Ensure correct notification provider if (!context.Notification.Type.Name.Equals(EmailNotifications.DocReport.Name, StringComparison.Ordinal)) { return(null); } // Create result var result = new CommandResult <ReportSubmission <Doc> >(); // Get email template const string templateId = "NewDocReport"; // Tasks run in a background thread and don't have access to HttpContext // Create a dummy principal to represent the user so we can still obtain // the current culture for the email var principal = await _claimsPrincipalFactory.CreateAsync((User)context.Notification.To); var culture = await _contextFacade.GetCurrentCultureAsync(principal.Identity); var email = await _localeStore.GetFirstOrDefaultByKeyAsync <LocaleEmail>(culture, templateId); if (email == null) { return(result.Failed( $"No email template with the Id '{templateId}' exists within the 'locales/{culture}/emails.json' file!")); } // Get reason given text var reasonText = S["No reason supplied"]; if (ReportReasons.Reasons.ContainsKey(context.Model.Why)) { reasonText = S[ReportReasons.Reasons[context.Model.Why]]; } // Build topic url var baseUri = await _capturedRouterUrlHelper.GetBaseUrlAsync(); var url = _capturedRouterUrlHelper.GetRouteUrl(baseUri, new RouteValueDictionary() { ["area"] = "Plato.Docs", ["controller"] = "Home", ["action"] = "Display", ["opts.id"] = context.Model.What.Id, ["opts.alias"] = context.Model.What.Alias }); // Build message from template var message = email.BuildMailMessage(); message.Body = string.Format( email.Message, context.Notification.To.DisplayName, context.Model.What.Title, reasonText.Value, context.Model.Who.DisplayName, context.Model.Who.UserName, baseUri + url); message.IsBodyHtml = true; message.To.Add(new MailAddress(context.Notification.To.Email)); // Send message var emailResult = await _emailManager.SaveAsync(message); if (emailResult.Succeeded) { return(result.Success(context.Model)); } return(result.Failed(emailResult.Errors?.ToArray())); }
public override async Task <CommandResult> Execute() { var history = await jobsDataService.GetJobHistory(JobId); return(CommandResult.CreateSuccessResult(history)); }
public async Task <CommandResult <TError> > ExecuteAsync <TCommand>(TCommand command) where TCommand : Command { if (this is IAsyncCommandExecutor <TCommand, TError> || this is ICommandExecutor <TCommand, TError> ) { await RehydrateAsync().ConfigureAwait(false); // Idempotency check if (command.Id != default && commandsContainer != null) { var recievedCommand = await commandsContainer.GetItemViaStreamAsync <TCommand>(command.Id.ToString(), commandsPartitionKey).ConfigureAwait(false); if (recievedCommand != null) { return(new CommandResult <TError>(default(TError), null) { EventSourcingError = Error.IdempotencyFailure }); } } // Execute Command if (command.Time == default) { command.Time = DateTime.UtcNow; command.AggregateVersionWhenExecuted = LastAppliedEventNumber; } CommandResult <TError> result = null; if (this is IAsyncCommandExecutor <TCommand, TError> asyncCommandExecutor) { result = await asyncCommandExecutor.ExecuteCommandAsync(command).ConfigureAwait(false); } else if (this is ICommandExecutor <TCommand, TError> commandExecutor) { result = commandExecutor.ExecuteCommand(command); } // Persist Events List <Event> appliedEvents = new List <Event>(); foreach (var @event in result.Events) { @event.CommandId = command.Id; @event.Time = command.Time; var method = this.GetType().GetMethodsThroughHierarchy().Where(m => m.Name == nameof(ApplyAndPersistEventAsync)).Single(); var res = await((Task <Error>)method.Invoke(this, new object[] { @event })).ConfigureAwait(false); if (res == Error.ConsistencyConflict) { // Failed, we undo the persisted ones. foreach (var appliedEvent in appliedEvents) { await ReverseEventAsync(appliedEvent).ConfigureAwait(false); } await LoadSnapshotAsync().ConfigureAwait(false); await RehydrateAsync().ConfigureAwait(false); await SnapshotAsync().ConfigureAwait(false); return(new CommandResult <TError>(result.CommandError, null) { EventSourcingError = res }); } else if (res == Error.None) { // This one persisted appliedEvents.Add(@event); } } await SnapshotAsync().ConfigureAwait(false); // Persist Command if (command.Id != default && commandsContainer != null) { command.PartitionKey = commandsPartitionKey; var statusCode = await commandsContainer.CreateItemViaStreamAsync(command, true).ConfigureAwait(false); if ((int)statusCode.StatusCode < 200 || (int)statusCode.StatusCode >= 300) { // Reverting Events foreach (var @event in result.Events) { await ReverseEventAsync(@event).ConfigureAwait(false); } await LoadSnapshotAsync().ConfigureAwait(false); await RehydrateAsync().ConfigureAwait(false); await SnapshotAsync().ConfigureAwait(false); return(new CommandResult <TError>(result.CommandError, result.Events.ToArray()) { EventSourcingError = Error.IdempotencyFailure }); } } return(result); } return(new CommandResult <TError>(default(TError), null) { EventSourcingError = Error.ConsistencyConflict }); }
private static void LogFailedCommand(string msg, CommandResult cmdResult) { Log.LogError("{0} Command exit code: {1}\nStdout: {2}\nStderr: {3}", msg, cmdResult.ExitCode, cmdResult.StandardOutput, cmdResult.StandardError); }
public override async Task <CommandResult> Execute() { return(CommandResult.CreateSuccessResult(await dataService.GetAll())); }
public static BundleArch GetArchSelection(this CommandResult commandResult) { var archSelection = new[]
public static int DiffCommand(Config config) { string diffString = "System.Private.CoreLib.dll"; if (config.DoFrameworks) { diffString += ", framework assemblies"; } if (config.DoTestTree) { diffString += ", " + config.TestRoot; } Console.WriteLine("Beginning diff of {0}!", diffString); // Add each framework assembly to commandArgs // Create subjob that runs mcgdiff, which should be in path, with the // relevent coreclr assemblies/paths. string frameworkArgs = String.Join(" ", s_frameworkAssemblies); string testArgs = String.Join(" ", s_testDirectories); List<string> commandArgs = new List<string>(); // Set up CoreRoot commandArgs.Add("--platform"); commandArgs.Add(config.CoreRoot); commandArgs.Add("--output"); commandArgs.Add(config.OutputPath); if (config.HasBaseExeutable) { commandArgs.Add("--base"); commandArgs.Add(config.BaseExecutable); } if (config.HasDiffExecutable) { commandArgs.Add("--diff"); commandArgs.Add(config.DiffExecutable); } if (config.DoTestTree) { commandArgs.Add("--recursive"); } if (config.Verbose) { commandArgs.Add("--verbose"); } if (config.CoreLibOnly) { string coreRoot = config.CoreRoot; string fullPathAssembly = Path.Combine(coreRoot, "System.Private.CoreLib.dll"); commandArgs.Add(fullPathAssembly); } else { // Set up full framework paths foreach (var assembly in s_frameworkAssemblies) { string coreRoot = config.CoreRoot; string fullPathAssembly = Path.Combine(coreRoot, assembly); if (!File.Exists(fullPathAssembly)) { Console.WriteLine("can't find framework assembly {0}", fullPathAssembly); continue; } commandArgs.Add(fullPathAssembly); } if (config.TestRoot != null) { foreach (var dir in s_testDirectories) { string testRoot = config.TestRoot; string fullPathDir = Path.Combine(testRoot, dir); if (!Directory.Exists(fullPathDir)) { Console.WriteLine("can't find test directory {0}", fullPathDir); continue; } commandArgs.Add(fullPathDir); } } } Console.WriteLine("Diff command: {0} {1}", s_asmTool, String.Join(" ", commandArgs)); Command diffCmd = Command.Create( s_asmTool, commandArgs); // Wireup stdout/stderr so we can see outout. diffCmd.ForwardStdOut(); diffCmd.ForwardStdErr(); CommandResult result = diffCmd.Execute(); if (result.ExitCode != 0) { Console.WriteLine("Dasm command returned with {0} failures", result.ExitCode); return result.ExitCode; } // Analyze completed run. if (config.DoAnalyze == true) { List<string> analysisArgs = new List<string>(); analysisArgs.Add("--base"); analysisArgs.Add(Path.Combine(config.OutputPath, "base")); analysisArgs.Add("--diff"); analysisArgs.Add(Path.Combine(config.OutputPath, "diff")); analysisArgs.Add("--recursive"); Console.WriteLine("Analyze command: {0} {1}", s_analysisTool, String.Join(" ", analysisArgs)); Command analyzeCmd = Command.Create(s_analysisTool, analysisArgs); // Wireup stdout/stderr so we can see outout. analyzeCmd.ForwardStdOut(); analyzeCmd.ForwardStdErr(); CommandResult analyzeResult = analyzeCmd.Execute(); } return result.ExitCode; }
public CommandResultAssertions(CommandResult commandResult) { _commandResult = commandResult; }
public override async Task <CommandResult> ProceedMessageAsync(Message eMessage, Player player, CommandResult commandResult) { CommandProcess(player, commandResult); return(commandResult); }
public override async Task <CommandResult> ProceedCallbackAsync(CallbackQuery eCallbackQuery, Player player, CommandResult commandResult) { return(commandResult); }
public async Task CommandResultExtensions_Apply() { var context = TestHelpers.CreateHttpContext(); var state = new StoredRequestState( new EntityId("https://idp.example.com"), new Uri("https://sp.example.com/ReturnUrl"), new Saml2Id(), new Dictionary <string, string>() { { "Key1", "Value1" }, { "Key2", "value2" } }); var redirectLocation = "https://destination.com/?q=http%3A%2F%2Fexample.com"; var commandResult = new CommandResult() { HttpStatusCode = System.Net.HttpStatusCode.Redirect, Location = new Uri(redirectLocation), SetCookieName = "Saml2.123", RelayState = "123", RequestState = state, ContentType = "application/json", Content = "{ value: 42 }", ClearCookieName = "Clear-Cookie", Principal = new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, "SomerUser") }, "authType")), RelayData = new Dictionary <string, string>() { { "Relayed", "Value" } } }; ClaimsPrincipal principal = null; AuthenticationProperties authProps = null; var authService = Substitute.For <IAuthenticationService>(); context.RequestServices.GetService(typeof(IAuthenticationService)) .Returns(authService); await authService.SignInAsync( context, "TestSignInScheme", Arg.Do <ClaimsPrincipal>(p => principal = p), Arg.Do <AuthenticationProperties>(ap => authProps = ap)); await commandResult.Apply(context, new StubDataProtector(), "TestSignInScheme", null); var expectedCookieData = HttpRequestData.ConvertBinaryData( StubDataProtector.Protect(commandResult.GetSerializedRequestState())); context.Response.StatusCode.Should().Be(302); context.Response.Headers["Location"].SingleOrDefault() .Should().Be(redirectLocation, "location header should be set"); context.Response.Cookies.Received().Append( "Saml2.123", expectedCookieData, Arg.Is <CookieOptions>(co => co.HttpOnly && co.SameSite == SameSiteMode.None)); context.Response.Cookies.Received().Delete("Clear-Cookie"); context.Response.ContentType .Should().Be("application/json", "content type should be set"); context.Response.Body.Seek(0, SeekOrigin.Begin); new StreamReader(context.Response.Body).ReadToEnd() .Should().Be("{ value: 42 }", "content should be set"); principal.HasClaim(ClaimTypes.NameIdentifier, "SomerUser").Should().BeTrue(); authProps.Items["Relayed"].Should().Be("Value"); authProps.RedirectUri.Should().Be(redirectLocation); }
internal static CommandPosExecuteEvent CallCommandPosExecute(ICommand command, ref ICommandArgs cmdArgs, ref ICommandSource commandSource, ref CommandResult result) { var evt = new CommandPosExecuteEvent(command, cmdArgs, commandSource, result); OnCommandPosExecute?.Invoke(evt); cmdArgs = evt.Arguments; commandSource = evt.Source; result = evt.Result; return(evt); }