protected static Option <TPayload> CommandError <C> (TSpec spec, string template, C content, [CallerFilePath] string callerFile = null, [CallerMemberName] string callerName = null) => none <TPayload>(AppMessage.Error(template, content, callerFile, callerName));
public FileCopyResult(FilePath SrcPath, FilePath DstPath, string ErrorMessage) : base(AppMessage.Error(ErrorMessage)) { this.SrcPath = SrcPath; this.DstPath = DstPath; this.Replaced = false; }
/// <summary> /// Executes until the agent is cancelled /// </summary> protected virtual void Spin() { var MaxSpinnerCount = 5; try { while (!IsAgentCancelling) { var submissions = MutableList.Create <WorkPartition>(); if (Spinners.Count < MaxSpinnerCount) { submissions.AddRange(SubmitNext()); if (HasPendingTasks) { iter(ExecuteQueue(), task => { }); if (!DiagnosticMode) { SpinUpSpinner(); } } } CompleteRevolution(submissions.Count); } } catch (Exception e) { Notify(AppMessage.Error(e)); } }
/// <summary> /// Enqueues a collection of work items wherein each work item will be executed /// independently and returns a <see cref="Task"/> that will complete when all /// work submitted in the group has been completed. /// </summary> /// <param name="work">The work to be performed</param> /// <param name="worker">Invoked to perform each unit of work</param> /// <param name="observers">A listener for which appropriate actions will be invoked during execution</param> /// <returns></returns> protected Task <ReadOnlyList <WorkPartition> > SubmitGroup(IReadOnlyList <IPartitionedWork> work, Action <IPartitionedWork> worker, string groupName, IReadOnlyList <IWorkAgentObserver> observers) { return(Task.Factory.StartNew(() => { var tasks = work.Map(w => Submit(w, worker, observers)); try { ExecutingGroups.Add(groupName); iter(observers, observer => observer.RaiseGroupSubmitted(groupName)); tasks.WaitOn(ChildCancellation.Token); if (ExecutingGroups.Remove(groupName)) { iter(observers, observer => observer.RaiseGroupCompleted(groupName)); } } catch (OperationCanceledException) { Notify(TaskGroupExecutionCancelled(groupName)); } catch (Exception e) { Notify(AppMessage.Error(e)); } return tasks; })); }
Option <D> TryAddDispatch <D>(D d) where D : ICommandDispatch { if (Dispatches.TryAdd(d.SubmissionId, d)) { return(some(d)); } else { return(none <D>(AppMessage.Error("Can't add submission to dispatch queue"))); } }
/// <summary> /// Invokes an action when the message is nonempty /// </summary> /// <param name="action">The action to potentially invoke</param> /// <returns></returns> public Option <T> OnMessage(Action <IAppMessage> action) { if (!Message.IsEmpty) { action(Message); } else if (!Exists) { action(AppMessage.Error("No value")); } return(this); }
public static Task <CommandProcessExecutionLog> Invoke(FilePath ExecutablePath, string args, string workdir = null) { var proc = new Process { StartInfo = new ProcessStartInfo { FileName = ExecutablePath, Arguments = args, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = workdir ?? Environment.CurrentDirectory }, EnableRaisingEvents = true, }; var result = new CommandProcessExecutionLog(); proc.OutputDataReceived += (sender, e) => { if (isNotBlank(e.Data)) { result.StatusMessages.Add(e.Data); SystemConsole.Get().Write(AppMessage.Inform(e.Data)); } }; proc.ErrorDataReceived += (sender, e) => { if (isNotBlank(e.Data)) { result.ErrorMessages.Add(e.Data); SystemConsole.Get().Write(AppMessage.Error(e.Data)); } }; proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); return(Task.Run(() => { proc.WaitForExit(); result.ExitCode = proc.ExitCode; proc.Dispose(); return result; })); }
/// <summary> /// Defines a <see cref="IAppMessage"/> based on an exception /// </summary> /// <param name="e">The exception</param> /// <returns></returns> public static IAppMessage DefineExceptionMessage(this Exception e) { if (e is TargetInvocationException) { return(AppMessage.Error((e as TargetInvocationException).InnerException)); } else if (e.InnerException != null) { return(AppMessage.Error(e.InnerException)); } else { return(AppMessage.Error(e)); } }
public static ReadOnlyList <P> Items <P>(this Option <ReadOnlyList <P> > x, Action <IAppMessage> error) { if (x.IsSome()) { return(x.Items()); } else { var message = x.Message.IsEmpty ? AppMessage.Error("Required option has no value") : x.Message; error(message); return(ReadOnlyList.Create(new P[] { })); } }
public void ExecuteQueue(Action <ICommandResult <TSpec> > observer) { try { var commands = Dispatch(); while (commands.Count != 0) { Execute(commands).Iterate(observer); commands = Dispatch(); } } catch (Exception e) { Notify(AppMessage.Error(e)); throw; } }
public void Start() { try { if (AgentControlTask.IsNone()) { AgentControlTask = Task.Factory.StartNew(Spin, TaskCreationOptions.LongRunning); } else { Notify(AlreadyRunning()); } } catch (Exception e) { Notify(AppMessage.Error(e)); } }
static IAppMessage CompletedCommand(ICommandResult result, Option <CommandCompletion <TSpec, TPayload> > completion) { return(completion.Map( c => CommandStatusMessages.CompletedCommand(c), () => { if (result.Succeeded) { return CommandCompletionError(result, completion.Message); } if (!result.Succeeded) { return CommandExecutionAndCompletionError(result, completion.Message); } return AppMessage.Error("My logic is broken"); })); }
public static AgentControlTask Start(IApplicationContext C, IServiceAgent Agent) { var systemTask = task(() => { try { Agent.Start(); } catch (Exception e) { var message = AppMessage.Error(e); C.Notify(message); return(message); } return(inform("Complete")); }); return(new AgentControlTask(C, Agent, systemTask)); }
/// <summary> /// Writes text to a file /// </summary> /// <param name="path">The target path</param> /// <param name="text">The text to write</param> /// <param name="createDir">Specifies whether to create the target directory if it doesn't exist</param> /// <param name="overwrite">Specifies whether to overwrite an existing file</param> /// <returns></returns> public static FileWriteResult Write(this FilePath path, string text, bool createDir = true, bool overwrite = true) { try { //The path may just be a filename and the intent is //to emit to the current directory if (isBlank(Path.GetDirectoryName(path.FileSystemPath))) { File.WriteAllText(path, text); return(FileWriteResult.Success(path)); } else { if (createDir) { path.Folder.CreateIfMissing().Require(); } if (!overwrite) { if (path.Exists()) { return(FileWriteResult.Failure(path, AppMessage.Error($"The file {path} exists and the {nameof(overwrite)} option is false"))); } } else { File.WriteAllText(path, text); } return(FileWriteResult.Success(path)); } } catch (Exception e) { return(FileWriteResult.Failure(path, e)); } }
static IAppMessage DirectoryDoesNotExist(C spec) => AppMessage.Error($"Destination directory @DstDir does not exist and {nameof(spec.CreateDirectory)} is false", new { DstDir = Path.GetDirectoryName(spec.DstPath) });
static IAppMessage OrchestrationStartError(Type SpecType, Exception e) => AppMessage.Error("@CommandName orchestration start error: @ErrorDetail", new { CommandName = CommandSpecDescriptor.FromSpecType(SpecType).CommandName, ErrorDetail = e.ToString() });
/// <summary> /// Populates a None with exception content /// </summary> /// <param name="e">The reason for None</param> /// <returns></returns> public static Option <T> None(Exception e) => new Option <T>(AppMessage.Error(e.ToString()));
static IAppMessage SourceDoesNotExist(C spec) => AppMessage.Error("The source path @SrcPath does not exist", new { spec.SrcPath });
public static IAppMessage PathDoesNotExist(string Path) => AppMessage.Error("The path @Path does not exist", new { Path });
static IAppMessage CommandTypeNotFound(string CommandName) => AppMessage.Error("The command spec for the @CommandName command could not be found", new { CommandName });
/// <summary> /// Defines an error message based on an exception /// </summary> /// <param name="e">The exeption upon which the message will be based</param> /// <param name="callerFile">The file from which the call was made</param> /// <param name="callerName">The name of the invoking member</param> /// <returns></returns> public static IAppMessage error(Exception e, [CallerFilePath] string callerFile = null, [CallerMemberName] string callerName = null) => AppMessage.Error(e, callerFile, callerName);
static IAppMessage DestinationExists(C command) => AppMessage.Error($"Destination path @ArchivePath exists and {nameof(command.Overwrite)} is false", new { command.ArchivePath });
static IAppMessage CouldNotMaterialize(string CommandName, Json j) => AppMessage.Error("The @CommandName command could not be materialized from the block: @JsonBlock", new { CommandName, JsonBlock = j.Text });
public Y match <Y>(Func <X1, Y> f1, Func <X2, Y> f2, Func <X3, Y> f3) => (x1 ? x1.Map(f1) : x2 ? x2.Map(f2) : x3 ? x3.Map(f3) : fail <Y>(AppMessage.Error("No match"))).Require();
/// <summary> /// Defines a correlated error message with typed content /// </summary> /// <typeparam name="C">The content type</typeparam> /// <param name="CT">The correlation value</param> /// <param name="template">A content-bound template string</param> /// <param name="content">The typed content</param> /// <param name="callerFile">The file from which the call was made</param> /// <param name="callerName">The name of the invoking member</param> /// <returns></returns> public static IAppMessage error <C>(CorrelationToken CT, string template, C content, [CallerFilePath] string callerFile = null, [CallerMemberName] string callerName = null) => AppMessage.Error(CT, template, content, callerFile, callerName);
public static IAppMessage StringLengthMismatch(string x, int length) => AppMessage.Error($"The string '{x}' has length of {x.Length} which unfortunately does not equal the required length {length}");
public static FileWriteResult Failure(FilePath DstPath, Exception error) => new FileWriteResult(DstPath, AppMessage.Error(error));
static IAppMessage CommandSpecNameUnspecified(Json j) => AppMessage.Error("The command spec name could not be parsed from the block: @JsonBlock", new { JsonBlock = j.Text });
/// <summary> /// Defines a correlated error message based on an exception /// </summary> /// <param name="e">The exeption upon which the message will be based</param> /// <param name="callerFile">The file from which the call was made</param> /// <param name="callerName">The name of the invoking member</param> /// <returns></returns> public static IAppMessage error(CorrelationToken CT, Exception e, [CallerFilePath] string callerFile = null, [CallerMemberName] string callerName = null) => AppMessage.Error(CT, e, callerFile, callerName);
/// <summary> /// Defines an error message /// </summary> /// <param name="text">The message text</param> /// <param name="callerFile">The file from which the call was made</param> /// <param name="callerName">The name of the invoking member</param> /// <returns></returns> public static IAppMessage error(string text, [CallerFilePath] string callerFile = null, [CallerMemberName] string callerName = null) => AppMessage.Error(text, callerFile, callerName);