public ActionResult Create(CreateEquipmentInfoCommand command) { if (Request.Files.Count > 0) { command.Files = new List <FileInfo>(); for (int i = 0; i < Request.Files.Count; i++) { if (i == 0) { command.File = new FileInfo { FileBytes = Request.Files[i].ReadBytes(), FileName = Request.Files[i].FileName }; } else { command.Files.Add(new FileInfo { FileBytes = Request.Files[i].ReadBytes(), FileName = Request.Files[i].FileName }); } } } _commandService.Execute(command); return(RedirectToAction("Index")); }
public SemanticVersion ChocoVersion() { try { var version = SemanticVersion.Parse(m_command.Execute("choco", "--version", true, true)); return(version); } catch (Exception ex) { return(Constants.EmptySemanticVersion); } }
public SemanticVersion ChocoVersion() { try { var version = SemanticVersion.Parse(m_command.Execute("choco", "--version", true, true)); return(version); } catch (Exception ex) { Console.WriteLine(ex); m_logger.Warning("Could not parse local chocolatey version. ", ex); return(Constants.EmptySemanticVersion); } }
public void Execute(TranslateSubtitlesFileToNewFile command) { try { decoratee.Execute(command); } catch (AuthenticationException e) { notifier.Notify($"The authentication key \"{e.Key}\" is not valid. Please check your key in your DeepL Pro dashboard."); } catch (InternalErrorException) { notifier.Notify("An internal error occured. Please try again later."); } catch (FileNotFoundException e) { notifier.Notify($"The file \"{e.FileName}\" does not exist. Please give a correct srt file to translate."); } catch (SubtitlesParsingException e) { notifier.Notify($"Unable to parse the file \"{command.ToTranslate}\" because of a problem in the subtitle number {e.IncorrectSubtitleId}."); } catch (InternetAccessException) { notifier.Notify("Unable to reach the DeepL API. Please check your internet access."); } }
public ActionResult Register(RegisterModel model) { if (ModelState.IsValid) { try { var result = _commandService.Execute(new CreateAccount { Name = model.UserName, Password = model.Password, MillisecondsTimeout = 100000 }); if (result.IsCompleted && !result.HasError) { FormsAuthentication.SetAuthCookie(model.UserName, false); return(RedirectToAction("Index", "Home")); } else if (result.HasError) { ModelState.AddModelError("", result.ErrorMessage); } else if (!result.IsCompleted) { ModelState.AddModelError("", "用户注册处理超时。"); } } catch (CommandExecuteException ex) { if (ex.InnerException != null && ex.InnerException is DuplicateAccountNameException) { ModelState.AddModelError("", "该用户已被注册,请用其他账号注册。"); } } } return(View(model)); }
public void SetUp() { BootStrapper.BootUp(this, null); _service = NcqrsEnvironment.Get <ICommandService>(); _service.Execute(new CreateNewNote()); _rand = new Random(DateTime.Now.Millisecond); }
private void OnChatMessage(ref ChatMsg message, ref bool cancel) { // TODO player manager to cache these objects var player = new Player { Name = message.CustomAuthorName, SteamId = message.Author }; var text = message.Text; if (_commands.IsCommand(text)) { _commands.Execute(player, text.TrimStart(CommandPrefix), s => SendMessageTo(s, player.SteamId)); cancel = true; } else { var e = new ChatMessageEvent(message.Author, message.CustomAuthorName, text); ChatMessageReceived?.Invoke(ref e); cancel |= e.IsCancelled; if (!cancel) { _chatLog.Info($"{e.SenderName}: {e.Content}"); } } }
public async Task Execute(IUserContext userContext, TCommand command) { _ = command ?? throw new ArgumentNullException(nameof(command)); _logger.LogInformation(command.GetType().Name); await _decoratee.Execute(userContext, command); }
private void ShowSelectedArticleFlu() { string url = ((Banalise)SelectedArticle).LienFlu; webBrowserService.Execute(new OpenWebPage { Url = url }); }
public void Index() { var adjustInventory = new AdjustInventory { Decrease = true, ProductId = Guid.NewGuid(), Quantity = 7 }; _adjustInventoryService.Execute(adjustInventory); }
public ActionResult LogOn(LoginCommand command, string returnUrl) { _commandService.Execute(command); FormsAuthentication.SetAuthCookie(command.Username, createPersistentCookie: false); if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\")) { return(Redirect(returnUrl)); } return(RedirectToAction("Index", "Home")); }
public override void Execute() { if (string.IsNullOrEmpty(this.FilePath)) { return; } ICommandService commandService = this.services.GetService(typeof(ICommandService)) as ICommandService; commandService.SetCommandProperty(this.executionCommand, "FilePath", (object)this.FilePath); commandService.Execute(this.executionCommand, CommandInvocationSource.Internally); commandService.SetCommandProperty(this.executionCommand, "FilePath", (object)null); }
private void Process(TextPoint startPoint, TextPoint endPoint) { try { var result = ""; var methodName = GetMethodName(startPoint, endPoint); var className = GetClassName(startPoint, endPoint); result = string.Format("Processing method {0} in class {1}{2}{3}{2}{2}", methodName, className, Environment.NewLine, "-----------------------------------"); serviceProxy.Execute(result); var executable = GetProjectExecutable(applicationObject.ActiveDocument.ProjectItem.ContainingProject, applicationObject.ActiveDocument.ProjectItem.ContainingProject.ConfigurationManager.ActiveConfiguration); if (!File.Exists(executable)) { return; } try { AppDomainSetup appDomainSetup = new AppDomainSetup(); string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); appDomainSetup.ApplicationBase = Path.GetFullPath(path); var ad = AppDomain.CreateDomain("New Domain", null, appDomainSetup); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); var type = typeof(AssemblyProxy); var proxy = (AssemblyProxy)ad.CreateInstanceAndUnwrap(type.Assembly.FullName, type.FullName); result += proxy.LoadInfoFromAssembly(executable, className, methodName); AppDomain.Unload(ad); serviceProxy.Execute(result); } catch { } } catch { } }
public override IAsyncResult BeginExecute(Request request, AsyncCallback callback, object state) { var responseTask = new TaskCompletionSource <Response>(); BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState) { if (_commandService.WaitingRequests > ConfigurationSettings.MaxRequests) { responseTask.SetResult(Response.ServerTooBusy); return(CreateInnerAsyncResult(asyncCallback, asyncState)); } Type type; if (!BasicTypes.CommandTypes.TryGetValue(request.Header.GetIfKeyNotFound("Type"), out type)) { responseTask.SetResult(Response.UnknownType); return(CreateInnerAsyncResult(asyncCallback, asyncState)); } ICommand command; try { command = (ICommand)_serializer.Deserialize(request.Body, type); } catch (Exception) { responseTask.TrySetResult(Response.ParsingFailure); return(CreateInnerAsyncResult(asyncCallback, asyncState)); } var timeout = request.Header.GetIfKeyNotFound("Timeout", "0").ChangeIfError(0); var returnMode = (CommandReturnMode)request.Header.GetIfKeyNotFound("Mode", "1").ChangeIfError(1); var result = _commandService.Execute(command, returnMode, timeout); var message = _serializer.Serialize(result); responseTask.TrySetResult(new Response(200, message)); return(CreateInnerAsyncResult(asyncCallback, asyncState)); }; EndInvokeDelegate <Response> endDelegate = delegate { return(responseTask.Task.Result); }; return(WrappedAsyncResult <Response> .Begin( callback, state, beginDelegate, endDelegate, null, Timeout.Infinite)); }
private void ExecuteCommand() { try { _service.Execute(new ChangeNoteText { NoteId = _guid, NewText = "SomeText" }); } catch (ConcurrencyException ex) { Console.WriteLine(ex.Message); ExecuteCommand(); } }
public void InstallPrinter(string printerPath) { if (string.IsNullOrEmpty(printerPath)) { throw new ArgumentException("Path cannot be null or empty", nameof(printerPath)); } string cmdPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "rundll32.exe"); CommandExecutionResult executionResult = _commandService.Execute(cmdPath, "printui.dll,PrintUIEntry", "/in", $"/n\"{printerPath}\""); // ReSharper disable once InvertIf if (!executionResult.Success) { var message = string.Join(Environment.NewLine, executionResult.Output); throw new InstallPrinterFailedException(printerPath, message); } }
public ExecuteResponse Execute(ExecuteRequest executeRequest) { Contract.Requires(executeRequest != null); Contract.Requires(executeRequest.Command != null); Contract.Ensures(Contract.Result <ExecuteResponse>() != null); Contract.EnsuresOnThrow <FaultException <CommandWebServiceFault> >(Contract.Result <ExecuteResponse>() == null); try { _service.Execute(executeRequest.Command); return(new ExecuteResponse()); } catch (Exception ex) { throw new FaultException <CommandWebServiceFault>( new CommandWebServiceFault(executeRequest.Command, ex), "An exception occured while trying to execute the command"); } }
static void Main(string[] args) { _handler = new Handler(); BootStrapper.BootUp(_handler, new TextChangedHandler()); _service = NcqrsEnvironment.Get <ICommandService>(); _service.Execute(new CreateNewNote()); _rand = new Random(DateTime.Now.Millisecond); ExecuteCommand(1); int i; for (i = 0; i < 10000; i++) { ThreadPool.QueueUserWorkItem(cb => ExecuteCommand(1)); //The wait time is exponentially distributed, meaning that commands are Poisson distributed. var time = -(Math.Log(_rand.NextDouble()) * 1000) / AvgRatePerSecond; Thread.Sleep((int)time); } }
private static void ExecuteCommand(int times) { try { _service.Execute(new ChangeNoteText { NoteId = _handler.Guid, NewText = times.ToString() }); } catch (Exception ex) { if (!(ex is ConcurrencyException) && !(ex.InnerException is ConcurrencyException)) { Console.WriteLine(ex.Message); } times++; ThreadPool.QueueUserWorkItem(cb => ExecuteCommand(times)); } }
public void Execute(TranslateSubtitlesFileToNewFile command) { if (command == null) { throw new ArgumentNullException(nameof(command)); } var cost = costCalculator.Calculate(command.ToTranslate); var answer = confirmationService.AskForConfirmation( $"The translation cost for \"{command.ToTranslate}\" is {cost}. Do you wan't to translate ?"); if (answer == Answer.No) { return; } decoratee.Execute(command); }
private void RunInSandbox(string code) { StartCodeService(); var doRestart = false; var serviceResult = "timeout"; var invocationThread = new Thread(() => { Thread.CurrentThread.CurrentCulture = new CultureInfo("en"); Thread.CurrentThread.CurrentUICulture = new CultureInfo("en"); try { serviceResult = _serviceProxy.Execute(code); } catch (EndpointNotFoundException ex) { doRestart = true; } catch (Exception ex) { _serviceProxy = null; } }); invocationThread.Start(); invocationThread.Join(6000); if (doRestart) { _serviceProxy = null; RunInSandbox(code); } else { if (string.IsNullOrEmpty(serviceResult)) { serviceResult = "null"; } ResultView.Text = serviceResult; } }
private async Task MessageReceivedAsync(IDialogContext context, IAwaitable <object> result) { var activity = await result as Activity; try { //var _luis = new LuisService(); //var luis = await _luis.QueryLuis(activity.Text); //TakeTheJokeService joke = new TakeTheJokeService(); string rez = await _commandService.Execute(activity.Text); await context.PostAsync(rez); context.Wait(MessageReceivedAsync); } catch (Exception ex) { throw ex; } // return our reply to the user }
public void Execute(UpdateArticles command) { try { decoratedUpdater.Execute(command); } catch (InvalidUpdateSourceException) { ShowErrorToUser( "Sélectionnez d'abord un fichier Excel à partir duquel lancer la mise à jour."); } catch (FileOpenedByAnotherProcessException) { ShowErrorToUser( "Le fichier sélectionné est déjà ouvert dans un autre logiciel, peut-être Excel.\n" + "Fermez-le puis réessayez."); } catch (NotAnExcelFileException) { ShowErrorToUser( "Le fichier sélectionné n'est pas un fichier Excel."); } }
public void Handle(TCommand command) { try { //Mmmm. Dynamic is not usually OK, but here we want the inheritor to be able to specify an interface or base class, as the //message to be listened to, while still correctly dispatching the command to the correct handler... var commandResult = (CommandResult)_commandService.Execute((dynamic)command); _bus.Reply(new CommandSuccessResponse(commandId: command.Id, events: commandResult.Events.ToArray())); } catch (Exception e) { using (new TransactionScope(TransactionScopeOption.Suppress)) { if (e is DomainCommandValidationException) { var commandFailedException = e as DomainCommandValidationException; _bus.Reply(new CommandDomainValidationExceptionResponse { CommandId = command.Id, Message = commandFailedException.Message, InvalidMembers = commandFailedException.InvalidMembers.ToList() }); } else { //todo:Try to get retries working sanely here since it may be an intermittent error such as a timeout or deadlock etc... _bus.Reply(new CommandExecutionExceptionResponse { CommandId = command.Id }); } } throw; //This currently requires that retries is set to 0 to behave correctly. } }
public IActionResult ExecuteCommand([FromBody] Command command) { var result = _commandService.Execute(command); return(Ok(result)); }
public async Task Execute(IUserContext userContext, TCommand command) { CheckAuthorization(); await _decoratee.Execute(userContext, command); }
public async Task Execute(IUserContext userContext, TCommand command) { await _decoratee.Execute(userContext, command); await AppendToAuditTrail(command); }
protected CommandResult ExecuteCommand(ICommand command, int millisecondsDelay = 50000) { return(_commandService.Execute(command, millisecondsDelay)); }
public void DoSomething(Guid id) { _commandService.Execute(new DoSomething(id)); }
public void CreateNewNote(CreateNewNote command) { _service.Execute(command); }
public static void CommandQueuePoller(ICommandService service) { //Trace.WriteLine("LogPoller has started -- seeing if there's anything in the queue for me!!"); CloudQueueMessage msg = CommandQueue.GetMessage(); if (msg == null) { //Trace.TraceInformation("COMMAND QUEUE nothing found - going back to sleep"); } while (msg != null) { //do something string myMessage = msg.AsString; CommandQueue.DeleteMessage(msg); Trace.TraceInformation("Got message {0}", myMessage); //split the ID from the type -- first item is ID, second is type string[] messageParts = myMessage.Split(new char[] {':'}, StringSplitOptions.RemoveEmptyEntries); if (messageParts.Length!=2) { Trace.TraceError("COMMAND QUEUE message improperly formed. {0}", myMessage); continue; } CloudBlockBlob theBlob = CommandBlobContainer.GetBlockBlobReference(messageParts[0]); Type commandType = Type.GetType(messageParts[1]); CommandBase theCommand = null; using (MemoryStream msBlob = new MemoryStream()) { byte[] logBytes = theBlob.DownloadByteArray(); msBlob.Write(logBytes, 0, logBytes.Length); BinaryFormatter bf = new BinaryFormatter(); msBlob.Position = 0; object theObject = bf.Deserialize(msBlob); theCommand = Convert.ChangeType(theObject, commandType) as CommandBase; } if (theCommand != null) { service.Execute(theCommand); } else { Trace.TraceInformation("COMMAND BLOB Could not deserialize message from queue id {0}", myMessage); } msg = CommandQueue.GetMessage(); } }