public void CreateContactItem(string text, string tooltip, Vector3 position, float lifetime = -1f) { GameObject g = Instantiate(_contactItem, _canvas); g.transform.position = _camera.WorldToScreenPoint(position); g.GetComponentInChildren <Text>().text = text; g.GetComponent <GenericTooltipHandler>().Initialize( () => TooltipManager.getInstance.OpenTooltip(tooltip, Input.mousePosition), //should bring up tooltip () => CommandMapper.AddMove(position, !Input.GetKey(KeyCode.LeftShift)), delegate { if (Input.GetKey(KeyCode.LeftAlt)) { CommandMapper.SetAlignmentPlane(position.y); } else { CameraManager.getInstance.JumpTo(position, true); } }, null, () => TooltipManager.getInstance.CloseTooltip()); //should kill tooltip _contactItems.Add(new ContactItem(g, position)); if (lifetime > 0f) { Destroy(g, lifetime); } }
void OnInitialize() { _uiItem = Instantiate(_uiPrefab, WorldUIManager.getInstance.canvas); _uiItem.transform.Find("text").GetComponent <Text>().text = "[Unknown Signal]"; _uiItem.GetComponent <GenericTooltipHandler>().Initialize( null, //should bring up tooltip delegate { CommandMapper.AddMove(_entity.transform.position, !Input.GetKey(KeyCode.LeftShift)); if (_isDiscovered) { CommandMapper.SetResourceTarget(_entity); } }, delegate { if (Input.GetKey(KeyCode.LeftAlt)) { CommandMapper.SetAlignmentPlane(_entity.transform.position.y); } else { CameraManager.getInstance.JumpTo(_entity.transform.position, true); } }, null, null); //should kill tooltip InitializeAlignmentVisualization(); }
public ApiClient(IOptions <ApiClientConfiguration> configuration, TokenContainer token, HttpClient http, CommandMapper commandMapper, QueryMapper queryMapper, IExceptionHandler exceptionHandler, IEventDispatcher eventDispatcher, Interop interop, ILogFactory logFactory, Json json) { Ensure.NotNull(configuration, "configuration"); Ensure.NotNull(token, "token"); Ensure.NotNull(http, "http"); Ensure.NotNull(commandMapper, "commandMapper"); Ensure.NotNull(queryMapper, "queryMapper"); Ensure.NotNull(exceptionHandler, "exceptionHandler"); Ensure.NotNull(eventDispatcher, "eventDispatcher"); Ensure.NotNull(interop, "interop"); Ensure.NotNull(logFactory, "logFactory"); Ensure.NotNull(json, "json"); this.configuration = configuration.Value; this.token = token; this.http = http; this.commandMapper = commandMapper; this.queryMapper = queryMapper; this.exceptionHandler = exceptionHandler; this.eventDispatcher = eventDispatcher; this.interop = interop; this.log = logFactory.Scope("ApiClient"); this.json = json; http.BaseAddress = this.configuration.ApiUrl; EnsureAuthorization(); }
void IOleComponent.OnEnterState(uint uStateID, int fEnter) { if (uStateID == (uint)_OLECSTATE.olecstateModal) { CommandMapper.SetModal(fEnter != 0); } }
public void InsertDeviceCommand(Guid deviceGuid, JObject command) { if (deviceGuid == Guid.Empty) { throw new WebSocketRequestException("Please specify valid deviceGuid"); } if (command == null) { throw new WebSocketRequestException("Please specify command"); } var device = DataContext.Device.Get(deviceGuid); if (device == null || !IsNetworkAccessible(device.NetworkID)) { throw new WebSocketRequestException("Device not found"); } var commandEntity = CommandMapper.Map(command); commandEntity.Device = device; commandEntity.UserID = CurrentUser.ID; Validate(commandEntity); DataContext.DeviceCommand.Save(commandEntity); _commandSubscriptionManager.Subscribe(Connection, commandEntity.ID); _messageBus.Notify(new DeviceCommandAddedMessage(device.ID, commandEntity.ID)); command = CommandMapper.Map(commandEntity); SendResponse(new JProperty("command", command)); }
public static void Initialize() { //setup location RuntimeData.localMapData.Instantiate(); _fleets = new List <Fleet>(); _ships = new List <ShipEntity>(); //collect all entities _resources = Object.FindObjectsOfType <ResourceEntity>().ToList(); _lastSpeed = SimulationSpeed.Normal; //setup ui CommandMapper.Initialize(); //setup eventual fleets for (int i = 0; i < RuntimeData.localMapData.fleets.Count; i++) { AddFleet(RuntimeData.localMapData.fleets[i]); } //enable/disable leave status OnGameStatusUpdated?.Invoke(_ships.All(s => s.teamID == 0)); CameraManager.getInstance.JumpTo(_ships[0].transform.position, true); CoroutineSurrogate.getInstance.StartCoroutine(TickAICommanders()); CoroutineSurrogate.getInstance.StartCoroutine(TurnTickAsync()); SetSimulationSpeed(SimulationSpeed.Stopped); }
public void GetCommand() { var commandNoArgs = new Command { Name = "no-args", Path = "entry.exe" }; var commandArgs1 = new Command { Name = "args1", Path = "entry.exe", Arguments = { "--arg1", "long argument" } }; var commandArgs2 = new Command { Name = "args2", Path = "entry.exe", Arguments = { "--arg2", "long argument" } }; var provider = new CommandMapper("installation directory", new[] { commandNoArgs, commandArgs1, commandArgs2 }); provider.GetCommand("installation directory" + Path.DirectorySeparatorChar + "entry.exe", out string additionalArgs) .Should().BeSameAs(commandNoArgs); additionalArgs.Should().Be(""); provider.GetCommand("\"installation directory" + Path.DirectorySeparatorChar + "entry.exe\" --arg1", out additionalArgs) .Should().BeSameAs(commandNoArgs); additionalArgs.Should().Be("--arg1"); provider.GetCommand("\"installation directory" + Path.DirectorySeparatorChar + "entry.exe\" --arg1 \"long argument\" bla", out additionalArgs) .Should().BeSameAs(commandArgs1); additionalArgs.Should().Be("bla"); provider.GetCommand("\"installation directory" + Path.DirectorySeparatorChar + "entry.exe\" --arg2 \"long argument\" bla", out additionalArgs) .Should().BeSameAs(commandArgs2); additionalArgs.Should().Be("bla"); provider.GetCommand("Something" + Path.DirectorySeparatorChar + "else.exe", out additionalArgs) .Should().BeNull(); }
/// <summary> /// Collects data about default programs. /// </summary> /// <param name="commandMapper">Provides best-match command-line to <see cref="Command"/> mapping.</param> /// <param name="capabilities">The capability list to add the collected data to.</param> /// <param name="appName">Is set to the name of the application as displayed to the user; unchanged if the name was not found.</param> /// <exception cref="IOException">There was an error accessing the registry.</exception> /// <exception cref="UnauthorizedAccessException">Read access to the registry was not permitted.</exception> public void CollectDefaultPrograms(CommandMapper commandMapper, CapabilityList capabilities, ref string? appName) { #region Sanity checks if (capabilities == null) throw new ArgumentNullException(nameof(capabilities)); if (commandMapper == null) throw new ArgumentNullException(nameof(commandMapper)); #endregion // Ambiguity warnings if (ServiceAssocs.Count > 1) Log.Warn(Resources.MultipleDefaultProgramsDetected); foreach ((string service, string client) in ServiceAssocs) { using var clientKey = Registry.LocalMachine.OpenSubKey(DesktopIntegration.Windows.DefaultProgram.RegKeyMachineClients + @"\" + service + @"\" + client); if (clientKey == null) continue; if (string.IsNullOrEmpty(appName)) appName = (clientKey.GetValue("") ?? clientKey.GetValue(DesktopIntegration.Windows.DefaultProgram.RegValueLocalizedName))?.ToString(); capabilities.Entries.Add(new DefaultProgram { ID = client, Service = service, Verbs = {GetVerbs(clientKey, commandMapper)}, InstallCommands = GetInstallCommands(clientKey, commandMapper.InstallationDir) }); } }
void CreateGroupItem(int index) { ShipGroup group = CommandMapper.GetGroup(index); GameObject gi = Instantiate(_groupItem, null); gi.transform.SetParent(_groups); gi.transform.Find("header").transform.Find("header").GetComponent <Text>().text = "[GROUP]: " + index; gi.transform.Find("header").transform.Find("header").GetComponent <GenericTooltipHandler>().Initialize( () => TooltipManager.getInstance.OpenTooltip("[<color=yellow>LEFT-CLICK</color>] to select.\n[<color=yellow>SCROLL-CLICK</color>] to focus.", Input.mousePosition), () => CommandMapper.SelectGroup(index), () => CameraManager.getInstance.JumpTo(CommandMapper.GetGroup(index).GetCenter(), true), null, () => TooltipManager.getInstance.CloseTooltip()); gi.transform.Find("header").transform.Find("remove").GetComponent <GenericTooltipHandler>().Initialize( () => TooltipManager.getInstance.OpenTooltip("Remove group.", Input.mousePosition), () => CommandMapper.RemoveGroup(index), null, null, () => TooltipManager.getInstance.CloseTooltip()); Transform list = gi.transform.Find("list"); for (int i = 0; i < group.ships.Count; i++) { CreateGroupShipItem(list, group.ships[i]); } _groupItems[index] = gi; _groupItems[index].transform.SetSiblingIndex(index); UpdateGroupsVisibility(); }
static void Main(string[] args) { var allCommands = TypeHelper.GetAllTypesInheritedFromType <ICommand>().Where(x => x.IsClass); var allExecutors = TypeHelper.GetAllTypesInheritedFromType <IExecutor>().Where(x => x.IsClass); var commandMap = allCommands.ToDictionary(k => k.Name.Replace("Command", string.Empty).ToLower(), v => v); var executorMap = allExecutors.ToDictionary(k => k.Name.Replace("Executor", string.Empty).ToLower(), v => (IExecutor)Activator.CreateInstance(v)); if (!ConfigHelper.CheckOrCreate("config.json")) { Console.WriteLine("Could not open or create config.json"); return; } var commandMapper = new CommandMapper(); if (args.Length == 0) { args = new[] { "help" }; } var commandType = commandMap[args[0].ToLower()]; var executor = executorMap[args[0].ToLower()]; var command = commandMapper.MapCommand(commandType, args.SubArray(1)); executor.Execute(command); }
public void UpdateDeviceCommand(int commandId, JObject command) { if (commandId == 0) { throw new WebSocketRequestException("Please specify valid commandId"); } if (command == null) { throw new WebSocketRequestException("Please specify command"); } var commandEntity = DataContext.DeviceCommand.Get(commandId); if (commandEntity == null || commandEntity.DeviceID != CurrentDevice.ID) { throw new WebSocketRequestException("Device command not found"); } CommandMapper.Apply(commandEntity, command); commandEntity.Device = CurrentDevice; Validate(commandEntity); DataContext.DeviceCommand.Save(commandEntity); _messageBus.Notify(new DeviceCommandUpdatedMessage(CurrentDevice.ID, commandEntity.ID)); command = CommandMapper.Map(commandEntity); SendResponse(new JProperty("command", command)); }
void OnRightClick() { if (_entity.isDiscovered) { CommandMapper.UpdateTarget(_entity); } }
private void Execute(CommandMapper mapper, CommandLine command) { var obj = mapper.CommandClassBuilder.Build(); var executor = mapper.ExecutorBuilder.CreateExecutor(obj); foreach (var kvp in command.Parameters) { var r = executor.SetParameter(kvp.Key, kvp.Value, this.Engine.MapperManager.GetAgent()); if (r.HasError) { this.WriteLine(r); return; } } var missing = executor.GetMissingParameters().ToArray(); if (missing.Length != 0) { this.Engine.GetCommandMember(z => z.MissingParametersFormater) .Format(this.Engine.GetCommandMember(z => z.Output), mapper, missing, this.Engine.GetCommandMember(z => z.CommandParameterParser)); this.Help(command); return; } executor.Execute(this, command); }
/// <summary> /// Collects data about context menu entries. /// </summary> /// <param name="commandMapper">Provides best-match command-line to <see cref="Command"/> mapping.</param> /// <param name="capabilities">The capability list to add the collected data to.</param> /// <exception cref="IOException">There was an error accessing the registry.</exception> /// <exception cref="UnauthorizedAccessException">Read access to the registry was not permitted.</exception> public void CollectContextMenus(CommandMapper commandMapper, CapabilityList capabilities) { #region Sanity checks if (capabilities == null) { throw new ArgumentNullException(nameof(capabilities)); } if (commandMapper == null) { throw new ArgumentNullException(nameof(commandMapper)); } #endregion using (var progIDKey = Registry.ClassesRoot.OpenSubKey(DesktopIntegration.Windows.ContextMenu.RegKeyClassesFiles)) { if (progIDKey == null) { throw new IOException("Registry key not found"); } foreach (string entry in ContextMenuFiles) { capabilities.Entries.Add(new ContextMenu { ID = "files-" + entry, Target = ContextMenuTarget.Files, Verbs = { GetVerb(progIDKey, commandMapper, entry) ?? throw new IOException($"Verb '{entry}' not found.") } });
public AnkhRuntime(IServiceContainer parentContainer) { if (parentContainer == null) { throw new ArgumentNullException("parentContainer"); } _container = parentContainer; _commandMapper = GetService <CommandMapper>(); if (_commandMapper == null) { _container.AddService(typeof(CommandMapper), _commandMapper = new CommandMapper(this)); } _context = GetService <AnkhContext>(); if (_context == null) { _container.AddService(typeof(AnkhContext), _context = AnkhContext.Create(this)); } InitializeServices(); if (_runtimeInstance == null) { _runtimeInstance = this; } }
public async Task <IActionResult> CreateDeliveryRequest(string transactionId, Contracts.DataStructures.Address address, CancellationToken cancellationToken) { var command = CommandMapper.ToServiceCommand(transactionId, address); await createDeliveryRequestCommandHandler.HandleAsync(command, cancellationToken).ConfigureAwait(false); return(NoContent()); }
void ProcessSecondaryKey() { //ignore UI clicks //if (EventSystem.current.IsPointerOverGameObject()) // return; CommandMapper.ClearSelection(); }
public void Format(IOutput output, CommandMapper commandMapper, IEnumerable<IParameterMapper> mappers, ICommandParameterParser parser) { foreach (var line in this.Format(commandMapper, mappers, parser)) { output.WriteLine(line); } }
/// <summary> /// Retrieves data about registered applications. /// </summary> /// <param name="commandMapper">Provides best-match command-line to <see cref="Command"/> mapping.</param> /// <param name="capabilities">The capability list to add the collected data to.</param> /// <param name="appName">Is set to the name of the application as displayed to the user; unchanged if the name was not found.</param> /// <param name="appDescription">Is set to a user-friendly description of the application; unchanged if the name was not found.</param> /// <exception cref="IOException">There was an error accessing the registry.</exception> /// <exception cref="UnauthorizedAccessException">Read access to the registry was not permitted.</exception> public AppRegistration?GetAppRegistration(CommandMapper commandMapper, CapabilityList capabilities, ref string?appName, ref string?appDescription) { #region Sanity checks if (capabilities == null) { throw new ArgumentNullException(nameof(capabilities)); } if (commandMapper == null) { throw new ArgumentNullException(nameof(commandMapper)); } #endregion // Ambiguity warnings if (RegisteredApplications.Count == 0) { return(null); } if (RegisteredApplications.Count > 1) { Log.Warn(Resources.MultipleRegisteredAppsDetected); } // Get registry path pointer string appRegName = RegisteredApplications[0]; string?capabilitiesRegPath = RegistryUtils.GetString(@"HKEY_LOCAL_MACHINE\" + DesktopIntegration.Windows.AppRegistration.RegKeyMachineRegisteredApplications, appRegName); if (string.IsNullOrEmpty(capabilitiesRegPath)) { return(null); } try { using var capsKey = RegistryUtils.OpenHklmKey(capabilitiesRegPath, out _); if (string.IsNullOrEmpty(appName)) { appName = capsKey.GetValue(DesktopIntegration.Windows.AppRegistration.RegValueAppName)?.ToString(); } if (string.IsNullOrEmpty(appDescription)) { appDescription = capsKey.GetValue(DesktopIntegration.Windows.AppRegistration.RegValueAppDescription)?.ToString(); } CollectProtocolAssocsEx(capsKey, commandMapper, capabilities); CollectFileAssocsEx(capsKey, capabilities); // Note: Contenders for StartMenu entries are detected elsewhere } catch (IOException ex) { Log.Warn(ex); } return(new() { ID = appRegName, CapabilityRegPath = capabilitiesRegPath }); }
/// <summary> /// Collects data about URL protocol handlers indicated by registered application capabilities. /// </summary> /// <param name="capsKey">A registry key containing capability information for a registered application.</param> /// <param name="commandMapper">Provides best-match command-line to <see cref="Command"/> mapping.</param> /// <param name="capabilities">The capability list to add the collected data to.</param> /// <exception cref="IOException">There was an error accessing the registry.</exception> /// <exception cref="UnauthorizedAccessException">Read access to the registry was not permitted.</exception> private static void CollectProtocolAssocsEx(RegistryKey capsKey, CommandMapper commandMapper, CapabilityList capabilities) { #region Sanity checks if (capsKey == null) { throw new ArgumentNullException(nameof(capsKey)); } if (commandMapper == null) { throw new ArgumentNullException(nameof(commandMapper)); } if (capabilities == null) { throw new ArgumentNullException(nameof(capabilities)); } #endregion using var urlAssocKey = capsKey.OpenSubKey(DesktopIntegration.Windows.AppRegistration.RegSubKeyUrlAssocs); if (urlAssocKey == null) { return; } foreach (string protocol in urlAssocKey.GetValueNames()) { string?progID = urlAssocKey.GetValue(protocol)?.ToString(); if (string.IsNullOrEmpty(progID)) { continue; } using var progIDKey = Registry.ClassesRoot.OpenSubKey(progID); if (progIDKey == null) { continue; } var prefix = new KnownProtocolPrefix { Value = protocol }; var existing = capabilities.GetCapability <UrlProtocol>(progID); if (existing == null) { var capability = new UrlProtocol { ID = progID, Descriptions = { progIDKey.GetValue("", defaultValue: "")?.ToString() ?? "" }, KnownPrefixes = { prefix } }; capability.Verbs.AddRange(GetVerbs(progIDKey, commandMapper)); capabilities.Entries.Add(capability); } else { existing.KnownPrefixes.Add(prefix); } } }
/// <summary> /// Retrieves data about a verb (an executable command) from the registry. /// </summary> /// <param name="typeKey">The registry key containing information about the file type / protocol the verb belongs to.</param> /// <param name="commandMapper">Provides best-match command-line to <see cref="Command"/> mapping.</param> /// <param name="verbName">The internal name of the verb.</param> /// <returns>The detected <see cref="Verb"/> or an empty <see cref="Verb"/> if no match was found.</returns> private static Verb?GetVerb(RegistryKey typeKey, CommandMapper commandMapper, string verbName) { #region Sanity checks if (typeKey == null) { throw new ArgumentNullException(nameof(typeKey)); } if (string.IsNullOrEmpty(verbName)) { throw new ArgumentNullException(nameof(verbName)); } if (commandMapper == null) { throw new ArgumentNullException(nameof(commandMapper)); } #endregion using var verbKey = typeKey.OpenSubKey(@"shell\" + verbName); if (verbKey == null) { return(null); } string?description = verbKey.GetValue("")?.ToString(); string?commandLine; using (var commandKey = verbKey.OpenSubKey("command")) { if (commandKey == null) { return(null); } commandLine = commandKey.GetValue("")?.ToString(); } if (string.IsNullOrEmpty(commandLine)) { return(null); } var command = commandMapper.GetCommand(commandLine, out string?additionalArgs); if (command == null) { return(null); } var verb = new Verb { Name = verbName, Command = (command.Name == Command.NameRun) ? null : command.Name, ArgumentsLiteral = additionalArgs }; if (!string.IsNullOrEmpty(description)) { verb.Descriptions.Add(description); } return(verb); }
public IEnumerable<FormatedString> Format(CommandMapper commandMapper, IEnumerable<IParameterMapper> mappers, ICommandParameterParser parser) { foreach (var mapper in mappers) { yield return $"{parser.GetInputSytle(mapper.Name)}\t\t\t{mapper.Desciption}"; yield return $" alias: {string.Join("; ", mapper.GetNames())}"; yield return ""; } }
public ViewHandlerDelegator( IPropertyMapper mapper, CommandMapper commandMapper, IPlatformViewHandler viewHandler) { _defaultMapper = mapper; _mapper = _defaultMapper; _commandMapper = commandMapper; _viewHandler = viewHandler; }
public void SetUp() { sp = new AnkhServiceProvider(); object pvar; var shell = new Mock <SVsShell>().As <IVsShell>(); shell.Setup(x => x.GetProperty(It.IsAny <int>(), out pvar)).Returns(-1); sp.AddService(typeof(SVsShell), shell.Object); var state = new Mock <IAnkhCommandStates>(); state.SetupGet(x => x.SccProviderActive).Returns(true); state.SetupGet(x => x.SolutionExists).Returns(true); sp.AddService(typeof(IAnkhCommandStates), state.Object); var selection = new Mock <ISelectionContext>(); selection.Setup(x => x.Cache[It.IsAny <object>()]).Returns(null); var rawHandle = new Mock <IVsSccProject2>(); var p = new SccProject("c:\foo\bar", rawHandle.Object); selection.Setup(x => x.GetSelectedProjects(It.IsAny <bool>())).Returns(new[] { p }); sp.AddService(typeof(ISelectionContext), selection.Object); var pcMgr = new Mock <IPendingChangesManager>(); sp.AddService(typeof(IPendingChangesManager), pcMgr.Object); var textMgr = new Mock <SVsTextManager>().As <IVsTextManager>(); sp.AddService(typeof(SVsTextManager), textMgr.Object); var selectionMonitor = new Mock <IVsMonitorSelection>(); sp.AddService(typeof(IVsMonitorSelection), selectionMonitor.Object); var r = new AnkhRuntime(sp); r.AddModule(new AnkhModule(r)); r.AddModule(new AnkhSccModule(r)); //r.AddModule(new AnkhVSModule(r)); r.AddModule(new AnkhUIModule(r)); r.AddModule(new AnkhDiffModule(r)); r.Start(); cm = r.GetService <CommandMapper>(); }
public void HandleCommandUpdate(int commandId) { var command = DataContext.DeviceCommand.Get(commandId); var connections = _commandSubscriptionManager.GetConnections(commandId); foreach (var connection in connections) { connection.SendResponse("command/update", new JProperty("command", CommandMapper.Map(command))); } }
void OnScrollClick() { if (Input.GetKey(KeyCode.LeftAlt)) { CommandMapper.SetAlignmentPlane(_entity.transform.position.y); } else { CameraManager.getInstance.JumpTo(_entity.transform.position, true); } }
void OnLeftClick() { if (_entity.teamID == 0) { CommandMapper.SelectShip(_entity, Input.GetKey(KeyCode.LeftShift), Input.GetKey(KeyCode.LeftControl)); } else { CommandMapper.AddMove(_entity.transform.position, !Input.GetKey(KeyCode.LeftShift)); } }
void InitializeShipSpeedSelections() { for (int i = 0; i < System.Enum.GetValues(typeof(SpeedSetting)).Length; i++) { int a = i; _shipSpeedSettings.transform.GetChild(i) .GetComponent <Button>() .onClick .AddListener(() => CommandMapper.UpdateCurrentSpeed((SpeedSetting)a)); } }
void OnUpdateDelete(object sender, CommandUpdateEventArgs e) { CommandMapper mapper = CommandMapper; if (mapper != null) { mapper.PerformUpdate(AnkhCommand.SvnNodeDelete, e); } else { e.Enabled = false; } }
public ApiController(FormatterContainer formatters, ICommandDispatcher commandDispatcher, IQueryDispatcher queryDispatcher, CommandMapper commandMapper, QueryMapper queryMapper) { Ensure.NotNull(formatters, "formatters"); Ensure.NotNull(commandDispatcher, "commandDispatcher"); Ensure.NotNull(queryDispatcher, "queryDispatcher"); Ensure.NotNull(commandMapper, "commandMapper"); Ensure.NotNull(queryMapper, "queryMapper"); this.formatters = formatters; this.commandDispatcher = commandDispatcher; this.queryDispatcher = queryDispatcher; this.commandMapper = commandMapper; this.queryMapper = queryMapper; }
void OnUpdateRename(object sender, CommandUpdateEventArgs e) { CommandMapper mapper = CommandMapper; if (mapper != null) { mapper.PerformUpdate(AnkhCommand.RenameRepositoryItem, e); } else { e.Enabled = false; } }
public async Task <ActionResult> Post(AddProductToOrderViewModel model) { var productsResponse = await GetAsync(HttpClients.ProductApi, "products"); var products = await productsResponse.ResultAsync <IEnumerable <ProductViewModel> >(); var command = CommandMapper.Map <AddProductToOrder>(model); command.Price = products.First(p => p.Sku == command.Sku).Price; command.UserId = Constants.DefaultUserId; await Bus.Send(command); return(Accepted()); }
/// <summary> /// Retrieves data about multiple verbs (executable commands) from the registry. /// </summary> /// <param name="typeKey">The registry key containing information about the file type / protocol the verbs belong to.</param> /// <param name="commandMapper">Provides best-match command-line to <see cref="Command"/> mapping.</param> /// <returns>A list of detected <see cref="Verb"/>.</returns> private static IEnumerable <Verb> GetVerbs(RegistryKey typeKey, CommandMapper commandMapper) { #region Sanity checks if (typeKey == null) { throw new ArgumentNullException(nameof(typeKey)); } if (commandMapper == null) { throw new ArgumentNullException(nameof(commandMapper)); } #endregion return(RegUtils.GetSubKeyNames(typeKey, "shell").Select(verbName => GetVerb(typeKey, commandMapper, verbName)).WhereNotNull()); }
private void HelpFor(CommandMapper mapper, Session session, CommandLine line) { if (mapper.HelpCommand.IsImplemented) { mapper.HelpCommand.GetInstance().Help(session, line); } else if (mapper.DesciptionCommand.IsImplemented) { session.WriteLine(" " + mapper.DesciptionCommand.GetInstance().Desciption); } else { var commandFormater = session.Engine.GetCommandMember(z => z.CommandFormater); foreach (var formatedString in commandFormater.Format(mapper)) { session.WriteLine(" " + formatedString); } } }
public void MappingTest(string commandLineArguments, ResultState expectedResult, string firstArgumentValue, ParserNotation notation) { // Setup var parser = new CommandParser(notation); var args = parser.Parse(commandLineArguments); var configuration = new CommandConfiguration(); configuration.CommandAssemblies.Add(Assembly.GetExecutingAssembly()); var lookup = new CommandLookup(configuration); var command = lookup.GetCommand(args.First().Key); Assert.NotNull(args); Assert.NotNull(command); // Test var target = new CommandMapper(); var result = target.Map(args.Skip(1), command.Arguments); // Assert Assert.NotNull(result); Assert.True(result.State == expectedResult); Assert.True(firstArgumentValue == null || firstArgumentValue == result?.ResultArguments?.First().ToString()); }
static void Main(string[] args) { if (args.Length == 0) { PrintUsage(); return; } var mapper = new CommandMapper(Console.Out); var action = mapper.Map(args); try { var task = action.Invoke(); task.Wait(); } catch (AggregateException ex) { Console.WriteLine(ex.Message); foreach (var exi in ex.InnerExceptions) { Console.WriteLine("- " + exi.Message); #if DEBUG Console.WriteLine("- " + exi.StackTrace); #endif } } catch (Exception ex) { Console.WriteLine(ex.Message); } #if DEBUG Console.ReadKey(); #endif }
internal static CommandExecutorBuilder TryCreate(CommandMapper mapper, ConverterAgent agent) { var builder = new CommandExecutorBuilder(mapper.CommandSource.SourceType); var dict = new Dictionary<string, bool>(); switch (mapper.CommandSource.SourceType) { case CommandSourceType.Class: var mappers = new List<PropertyParameterMapper>(); foreach (var property in mapper.CommandSource.ClassType.GetProperties()) { if (property.GetCustomAttribute<PropertyParameterAttribute>() != null) { if (!property.CanWrite) { Debug.WriteLine("parameter alway should can write!"); if (Debugger.IsAttached) Debugger.Break(); return null; } if (!agent.CanConvert(property.PropertyType)) { Debug.WriteLine($"parameter type [{property.PropertyType.Name}] missing converter."); if (Debugger.IsAttached) Debugger.Break(); return null; } var setter = new Action<object, object>(property.SetValue); var parameterMapper = new PropertyParameterMapper(property, property.PropertyType, setter); if (!parameterMapper.TryMap()) return null; foreach (var parameterName in parameterMapper.GetNames()) { if (dict.ContainsKey(parameterName)) { Debug.WriteLine($"parameter name {parameterName} was exists"); if (Debugger.IsAttached) Debugger.Break(); return null; } else { dict.Add(parameterName, false); } } mappers.Add(parameterMapper); } } mappers.Sort((x, y) => x.AttributeMapper.NameAttribute.Order.CompareTo( y.AttributeMapper.NameAttribute.Order)); builder.parameterMappers.AddRange(mappers); break; case CommandSourceType.Method: var method = ((MethodCommandSource)mapper.CommandSource).Method; foreach (var parameter in method.GetParameters()) { if (!JasilyConsoleEngine.IsDefaultParameters(parameter.ParameterType) && !agent.CanConvert(parameter.ParameterType)) { Debug.WriteLine($"parameter type [{parameter.ParameterType.Name}] missing converter."); if (Debugger.IsAttached) Debugger.Break(); return null; } var parameterMapper = new MethodParameterMapper(parameter); if (!parameterMapper.TryMap()) return null; foreach (var parameterName in parameterMapper.GetNames()) { if (dict.ContainsKey(parameterName)) { Debug.WriteLine($"parameter name {parameterName} was exists"); if (Debugger.IsAttached) Debugger.Break(); return null; } else { dict.Add(parameterName, false); } } builder.methodParameterSetter = (obj, args) => method.Invoke(obj, args); builder.parameterMappers.Add(parameterMapper); } break; default: throw new ArgumentOutOfRangeException(); } return builder; }
public void before() { mappings = new Mock<ICommandMappingList>(); subject = new CommandMapper(mappings.Object); }
public IEnumerable<FormatedString> Format(CommandMapper commandMapper) { yield return new FormatedString($"{commandMapper.Command}{this.GetIndent()}{commandMapper.Desciption}"); }
public IEnumerable<FormatedString> Format(CommandMapper commandMapper, IEnumerable<IParameterMapper> mappers, ICommandParameterParser parser) { var names = string.Join(", ", mappers.Select(z => z.Name)); yield return $"missing parameter: {names}."; }