public string SendCommand() { IServiceCommand command = _commands.Count > 0 ? _commands.Dequeue() : new ShutdownServerCommand(); string serializedCommand = command.SerializeToJsonString(); return(serializedCommand); }
/// <summary> /// Wrapper to set HavestRequestForcedWaitForApiThrotterling if it occurred /// </summary> /// <param name="commmand"></param> /// <param name="xmlParameter"></param> /// <returns></returns> string PerformRequest(IServiceCommand commmand, string xmlParameter = "") { var result = commmand.Exectue(xmlParameter); _forcedThrottleWaitForApiThrotterling = commmand.HavestRequestForcedWaitForApiThrotterling; return(result); }
static ServicePool() { var task = Task.Factory.StartNew(delegate(object cancellationToken) { IServiceCommand command = null; while (true) { manualEvent.WaitOne(); command = null; lock (syncObject) { if (queue.Count > 0) { command = queue.Dequeue(); } } if (command == null) { manualEvent.Reset(); continue; } try { command.Execute(); } catch (Exception ex) { ExceptionHandler.Default.Process(ex); } } }, null, TaskCreationOptions.LongRunning); }
protected void SendCommandSync(IServiceCommand request) { if (request != null) { ExecuteCommand(request); } }
//// =========================================================================================================== //// Methods //// =========================================================================================================== public async Task <IServiceCommandResponse> SendCommandAsync(IServiceCommand command) { var valueSet = new ValueSet(); command.SerializeToValueSet(valueSet); AppServiceResponse bridgeResponse = await _connection.SendMessageAsync(valueSet); AppServiceResponseStatus status = bridgeResponse.Status; IServiceCommandResponse response; if (status == AppServiceResponseStatus.Success) { if (!ServiceCommandResponse.TryDeserializeFromValueSet( bridgeResponse.Message, out response, out IServiceCommandResponse errorResponse)) { response = errorResponse; } } else { response = ServiceCommandResponse.CreateError(command.CommandName, ServiceErrorInfo.InternalError($"AppServiceConnection failed with status '{status}'")); } return(response); }
static ServicePool() { ThreadPool.QueueUserWorkItem(delegate { IServiceCommand command = null; while (true) { manualEvent.WaitOne(); command = null; lock (syncObject) { if (queue.Count > 0) { command = queue.Dequeue(); } } if (command == null) { manualEvent.Reset(); continue; } try { command.Execute(); } catch { } } }); }
public static void Add(IServiceCommand command) { lock (syncObject) { queue.Enqueue(command); manualEvent.Set(); } }
private string BuildArgs(IServiceCommand command) { var builder = new StringBuilder(); builder.Append("/attachDebugger"); return(builder.ToString()); }
public override IDbCommand GetCommand(IGxConnection con, string stmt, GxParameterCollection parameters) { IDbCommand cmd = base.GetCommand(con, stmt, parameters); IServiceCommand iCmd = cmd as IServiceCommand; if (iCmd != null) { iCmd.CursorDef = m_CursorDef; } return(cmd); }
protected void SendCommandAsync(IServiceCommand request) { if (request == null) { return; } var thread = new Thread(() => ExecuteCommand(request)); thread.Start(); }
//// =========================================================================================================== //// Methods //// =========================================================================================================== public async Task <IServiceCommandResponse> SendCommandAsync(IServiceCommand command, ILogger logger) { // The path to the elevated app is a zero-byte executable EXE that facilitates the packaged app launch for // classic invokers – such as CMD or Process.Start. string localAppDataPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string elevatedAppPath = Path.Combine( localAppDataPath, "microsoft", "windowsapps", "ElevatedDesktopServicesApp.exe"); string args = BuildArgs(command); var processStartInfo = new ProcessStartInfo { Arguments = args, FileName = elevatedAppPath, Verb = "runas", UseShellExecute = true }; int exitCode = 0; try { var elevatedProcess = Process.Start(processStartInfo); elevatedProcess?.WaitForExit(5000); exitCode = elevatedProcess?.ExitCode ?? 3; } catch (Exception e) { if (e.HResult == E_FAIL) { // the user cancelled the elevated process // by clicking "No" on the Windows elevation dialog exitCode = 1; } logger.LogError($"Error starting elevated process: {e}"); } ServiceCommandResponse response = exitCode == 0 ? ServiceCommandResponse.Create(command.CommandName, 0) : ServiceCommandResponse.CreateError( command.CommandName, new InvalidOperationException($"Error starting elevated process: {exitCode}")); return(await Task.FromResult(response)); }
//// =========================================================================================================== //// Methods //// =========================================================================================================== public static bool TryDeserializeFromJsonString( string jsonString, out IServiceCommand command, out IServiceCommandResponse errorResponse) { if (!BridgeMessageDeserializer.TryCreateFromJsonString( jsonString, out BridgeMessageDeserializer deserializer, out errorResponse)) { command = null; return(false); } return(TryDeserialize(deserializer, out command, out errorResponse)); }
public static bool TryDeserializeFromValueSet( IDictionary <string, object> valueSet, out IServiceCommand command, out IServiceCommandResponse errorResponse) { if (!BridgeMessageDeserializer.TryCreateFromValueSet( valueSet, out BridgeMessageDeserializer deserializer, out errorResponse)) { command = null; return(false); } return(TryDeserialize(deserializer, out command, out errorResponse)); }
/* * /// <summary> * /// 调用本地服务命令 * /// </summary> * /// <param name="commandType">命令类型</param> * /// <param name="commandResultType">命令响应类型</param> * /// <param name="commandData">命令实例</param> * /// <returns>是否执行成功</returns> * private bool TriggerServiceCommandLocal( * Type commandType, Type commandResultType, IServiceCommand commandData, * out ServiceCommandResultWithResponseContext commandResultData) * { * //TODO: 创建服务响应环境的上下文信息 * IServiceBusResponseContext responseContext = new BasicServiceBusResponseContext(); * * //从本地容器找 * IServiceCommandHandlerFactory handlerFactory = null; * bool isLocalExists = this._commandHandlerFactories.TryGetValue(commandType, out handlerFactory); * if (isLocalExists) * { * responseContext.IsFromLocalService = true; * IServiceCommandHandler commandHandler = handlerFactory.CreateHandler(); //服务实例(消费者) * * try * { * Type commandHandlerType = typeof(IServiceCommandHandler<,>).MakeGenericType(commandType, commandResultType); * MethodInfo method = commandHandlerType.GetMethod("HandlerCommand", new[] { commandType }); * var result = (IServiceCommandResult)method.Invoke(commandHandler, new object[] { commandData }); * result.CommandId = commandData.CommandId; //设置命令ID * * commandResultData = new ServiceCommandResultWithResponseContext(result, responseContext); * return true; * } * catch (Exception ex) * { * //TODO: 异常处理 * throw ex; * } * finally * { * //清理服务 * handlerFactory.ReleaseHandler(commandHandler); * } * } * commandResultData = null; * return false; //本地调用失败 * } */ /* * /// <summary> * /// 调用远程服务命令 * /// </summary> * /// <param name="serviceName">服务名称</param> * /// <param name="commandType">命令类型</param> * /// <param name="commandResultType">命令响应类型</param> * /// <param name="commandData">命令实例</param> * /// <returns>命令响应实例及响应上下文</returns> * private ServiceCommandResultWithResponseContext TriggerServiceCommandRemote( * string serviceName, Type commandType, Type commandResultType, IServiceCommand commandData) * { * //TODO: 创建服务响应环境的上下文信息 * IServiceBusResponseContext responseContext = new RemoteServiceBusResponseContext(); * * //1. TODO: 处理请求消息体 * byte[] requestMessageContent = null; * try * { * requestMessageContent = this.Serializer.Serialize(commandData).ToBytes(); * } * catch (Exception ex) * { * //TODO: 消息内容序列化失败 * throw new WindServiceBusException("Serialize command data failed !", ex); * } * * //2. 通过RPC框架执行远程调用 * byte[] responseMessageContent = null; * try * { * var rpcServerManager = this.IocResolver.Resolve<RpcServerManager>(); * RpcTransportMessage requestMessage = new RpcTransportMessage(commandData.CommandId) * { * MessageType = commandType.FullName, * MessageContent = requestMessageContent, * }; * RpcTransportMessage responseMessage = rpcServerManager.SendMessage(serviceName, requestMessage); * * //响应消息验证 * if (responseMessage == null || responseMessage.CorrelationMessageId == null || responseMessage.CorrelationMessageId != requestMessage.MessageId || responseMessage.MessageContent == null) || { || throw new WindServiceBusException(string.Format("request [{0}] get error response !", requestMessage.MessageId)); || } || responseMessageContent = responseMessage.MessageContent; || } || catch (WindServiceBusServiceNotFoundException notFoundEx) || { || //TODO: 未找到符合的远程服务 || throw notFoundEx; || } || catch (Exception ex) || { || //TODO: 其他异常处理 || throw ex; || } || || //3. 处理响应消息体 || IServiceCommandResult commandResult = null; || using (var responseStream = new MemoryStream(responseMessageContent)) || { || var obj = this.Serializer.Deserialize(commandResultType, responseStream); || commandResult = (IServiceCommandResult)obj; || } || || return new ServiceCommandResultWithResponseContext(commandResult, responseContext); ||} */ /// <summary> /// 执行命令服务核心 /// </summary> /// <typeparam name="TServiceCommand">命令服务类型</typeparam> /// <typeparam name="TCommandResult">命令服务返回结果类型</typeparam> /// <param name="commandData">命令服务数据</param> /// <param name="remoteContext">远端上下文(如果是本地调用,返回null)</param> /// <returns>命令服务返回结果数据</returns> internal IServiceCommandResult TriggerServiceCommandCore(Type commandType, Type commandResultType, IServiceCommand commandData, out RemoteServiceBusResponseContext remoteContext) { using (PerformanceCounter.BeginStopwatch(string.Format("localCall: {0}", commandType.FullName))) { //1. 本地调用 IServiceCommandResult commandResult = null; bool isTriggeredLocal = this.triggerLocalCommand(commandType, commandResultType, commandData, out commandResult); if (isTriggeredLocal) { remoteContext = null; return(commandResult); } } //2. 从远程容器找 try { using (PerformanceCounter.BeginStopwatch(string.Format("remoteCall: {0}", commandType.FullName))) { var resultWithContext = this.triggerRemoteCommand(commandType, commandResultType, commandData); remoteContext = resultWithContext.ResponseContext; return(resultWithContext.ServiceCommandResult); } } catch (WindServiceBusRpcException rpcException) { remoteContext = rpcException.RemoteContext; throw rpcException.InnerException; } catch (WindServiceBusMultiRpcException multiRpcException) { //处理多次调度异常信息 if (multiRpcException.Count == 1) { var rpcException = multiRpcException.First(); remoteContext = rpcException.RemoteContext; throw rpcException.InnerException; } else { throw multiRpcException; } } }
private static bool TryDeserialize( BridgeMessageDeserializer deserializer, out IServiceCommand command, out IServiceCommandResponse errorResponse) { switch (deserializer.CommandName) { case ServiceCommandName.ShutdownServer: command = new ShutdownServerCommand(); break; case ServiceCommandName.Echo: command = new EchoCommand(deserializer); break; case ServiceCommandName.RegistryReadIntValue: command = new RegistryReadIntValueCommand(deserializer); break; case ServiceCommandName.RegistryReadStringValue: command = new RegistryReadStringValueCommand(deserializer); break; case ServiceCommandName.RegistryWriteIntValue: command = new RegistryWriteIntValueCommand(deserializer); break; case ServiceCommandName.RegistryWriteStringValue: command = new RegistryWriteStringValueCommand(deserializer); break; case ServiceCommandName.Unknown: default: throw new InvalidOperationException( "This should be unreachable because the deserializer should have detected an invalid command name"); } if (deserializer.HadError) { command = null; } errorResponse = deserializer.LastError; return(!deserializer.HadError); }
public IServiceCommandResponse Execute(IServiceCommand command) { IServiceCommandResponse response; _logger.LogDebug("Executing command: ", command.ToDebugString()); switch (command) { case ShutdownServerCommand _: response = ServiceCommandResponse.Create(ServiceCommandName.ShutdownServer, true); break; case EchoCommand echoCommand: response = ServiceCommandResponse.Create(ServiceCommandName.Echo, echoCommand.EchoMessage); break; case RegistryReadIntValueCommand registryCommand: response = _registryExecutor.ExecuteRead(registryCommand, _logger); break; case RegistryReadStringValueCommand registryCommand: response = _registryExecutor.ExecuteRead(registryCommand, _logger); break; case RegistryWriteIntValueCommand registryCommand: response = _registryExecutor.ExecuteWrite(registryCommand, _logger); break; default: _logger.LogWarning("Unsupported command: ", command.CommandName); response = ServiceCommandResponse.CreateError( command.CommandName, ServiceErrorInfo.InternalError( $"Command '{command.CommandName}' is not supported for execution in the elevated bridge application.")); break; } return(response); }
internal bool triggerLocalCommand(Type commandType, Type commandResultType, IServiceCommand commandData, out IServiceCommandResult commandResult) { //命令参数验证规则 if (commandData == null) { throw new WindServiceBusException("command data empty error!", new ArgumentNullException("commandData")); } //从本地容器调用 var registry = this.IocResolver.Resolve <ServiceBusRegistry>(); bool isLocalCommand = registry.IsLocalServiceCommand(new ServiceUniqueNameInfo(commandType)); if (!isLocalCommand) { commandResult = null; return(false); } var localCommandDispatcher = this.createLocalDispatcher(registry); commandResult = localCommandDispatcher.DispatchCommand(commandType, commandResultType, commandData); return(true); }
private void ExecuteCommand(IServiceCommand command) { lock (_locker) { if (_tcpClient == null || !_tcpClient.Connected) { CurrentStatus = ServiceStatusEnum.Disconnected; return; } #if !DEBUG try { #endif command.Execute(_ssl); #if !DEBUG } catch { CurrentStatus = ServiceStatusEnum.Disconnected; } #endif } }
public ICollection <ServiceCommandResultWithResponseContext> BroadcastCommand(Type commandType, Type commandResultType, IServiceCommand commandData) { var commandUniqueName = new ServiceUniqueNameInfo(commandType); //1. 处理请求消息体 string requestMessageContent = this.serializer.SerializeString(commandData); //2. 服务调用 var responseCollection = this.BroadcastCommand(commandUniqueName, requestMessageContent); //3. 处理响应消息体 var commandResultCollection = responseCollection.Select(response => { var commandResult = (IServiceCommandResult)this.serializer.DeserializeString(commandResultType, response.ResponseMessageContent); return(new ServiceCommandResultWithResponseContext(commandResult, response.ResponseContext)); }).ToList(); return(commandResultCollection); }
public ServiceCommandResultWithResponseContext DispatchCommand(Type commandType, Type commandResultType, IServiceCommand commandData) { var commandUniqueName = new ServiceUniqueNameInfo(commandType); //1. 处理请求消息体 string requestMessageContent = this.serializer.SerializeString(commandData); //2. 服务调用 var response = this.DispatchCommand(commandUniqueName, requestMessageContent); //3. 处理响应消息体 var commandResult = (IServiceCommandResult)this.serializer.DeserializeString(commandResultType, response.ResponseMessageContent); return(new ServiceCommandResultWithResponseContext(commandResult, response.ResponseContext)); }
internal ServiceCommandResultWithResponseContext triggerRemoteCommand(Type commandType, Type commandResultType, IServiceCommand commandData) { var remoteCommandDispatcher = this.createRemoteDispatcher(); var resultWithContext = remoteCommandDispatcher.DispatchCommand(commandType, commandResultType, commandData); return(resultWithContext); }
protected void SendCommandAsync(IServiceCommand request) { if (request == null) return; var thread = new Thread(() => ExecuteCommand(request)); thread.Start(); }
internal IEnumerable <IServiceCommandResult> BroadcastServiceCommandCore(Type commandType, Type commandResultType, IServiceCommand commandData) { using (PerformanceCounter.BeginStopwatch(string.Format("localBroadcast: {0}", commandType.FullName))) { //1. 本地调用 IServiceCommandResult commandResult = null; bool isTriggeredLocal = this.triggerLocalCommand(commandType, commandResultType, commandData, out commandResult); if (isTriggeredLocal) { yield return(commandResult); } } using (PerformanceCounter.BeginStopwatch(string.Format("remoteBroadcast: {0}", commandType.FullName))) { //2. 远程调用 var remoteCommandDispatcher = this.createRemoteDispatcher(); var remoteResultList = remoteCommandDispatcher.BroadcastCommand(commandType, commandResultType, commandData); foreach (var remoteResult in remoteResultList) { yield return(remoteResult.ServiceCommandResult); } } }
private static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("Not enough arguments !"); return; } Config.Model = args[0].ToLower().UppercaseFirst(); var command = ""; if (args.Length > 1) { command = args[1].ToLower(); } if (args.Length > 2) { Config.Area = args[2].ToLower().UppercaseFirst(); } Config.ModelsPath = Environment.CurrentDirectory + "\\"; Config.ViewModelsPath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.FullName + "\\ViewModels\\"; Config.RepositoryPath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.FullName + "\\Repository\\"; Config.ServicePath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.FullName + "\\Service\\"; if (string.IsNullOrEmpty(Config.Area)) { Config.ControllerPath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.Parent.FullName + "\\Portal.Web\\Controllers\\"; Config.ViewsPath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.Parent.FullName + "\\Portal.Web\\Views\\" + Config.Model + "\\"; } else { Config.ControllerPath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.Parent.FullName + "\\Portal.Web\\Areas\\" + Config.Area + "\\Controllers\\"; Config.ViewsPath = new System.IO.DirectoryInfo(Config.ModelsPath).Parent.Parent.Parent.FullName + "\\Portal.Web\\Areas\\" + Config.Area + "\\Views\\" + Config.Model + "\\"; } var viewsDir = new System.IO.DirectoryInfo(Config.ViewsPath); if (!viewsDir.Exists) { viewsDir.Create(); } Config.PropertyNames = ClassHelper.GetPropertyNames(Config.ModelsPath + Config.Model + ".cs"); Config.PropertyTypes = ClassHelper.GetPropertyTypes(Config.ModelsPath + Config.Model + ".cs"); Config.PropertyDeclarations = ClassHelper.GetPropertyDeclarations(Config.ModelsPath + Config.Model + ".cs"); switch (command) { case "sr": case "service": var iserviceCommand = new IServiceCommand(); var serviceCommand = new ServiceCommand(); iserviceCommand.Execute(); serviceCommand.Execute(); break; case "rp": case "repository": var irepositoryCommand = new IRepositoryCommand(); var repositoryCommand = new RepositoryCommand(); irepositoryCommand.Execute(); repositoryCommand.Execute(); break; case "vm": case "viewmodel": var viewModelCommand = new ViewModelCommand(); viewModelCommand.Execute(); break; case "ad": case "addmodel": var addModel = new AddModelCommand(); addModel.Execute(); break; case "vi": case "views": var indexCommand = new IndexCommand(); var createCommand = new CreateCommand(); var editCommand = new EditCommand(); var deleteCommand = new DeleteCommand(); var detailsCommand = new DetailsCommand(); indexCommand.Execute(); createCommand.Execute(); editCommand.Execute(); deleteCommand.Execute(); detailsCommand.Execute(); break; case "cr": case "controller": var controllerCommand = new ControllerCommand(); controllerCommand.Execute(); break; case "go": default: var goCommand = new GoCommand(); goCommand.Execute(); break; } }
public Question(IServiceCommand ask, IRxn onSuccess = null, IRxn onFailure = null) { OnSuccess = onSuccess; Ask = ask; OnFailure = onFailure; }
/// <summary> /// Wrapper to set HavestRequestForcedWaitForApiThrotterling if it occurred /// </summary> /// <param name="commmand"></param> /// <param name="xmlParameter"></param> /// <returns></returns> string PerformRequest(IServiceCommand commmand, string xmlParameter = "") { var result = commmand.Exectue(xmlParameter); _forcedThrottleWaitForApiThrotterling = commmand.HavestRequestForcedWaitForApiThrotterling; return result; }
/// <summary> /// 派发服务命令 /// </summary> /// <param name="commandType">命令类型</param> /// <param name="commandResultType">命令响应类型</param> /// <param name="commandData">命令实例</param> /// <returns>命令响应实例</returns> public IServiceCommandResult DispatchCommand(Type commandType, Type commandResultType, IServiceCommand commandData) { var commandName = new ServiceUniqueNameInfo(commandType); ServiceCommandTypeInfo commandTypeInfo; bool isLocalCommandFound = this.registry.IsLocalServiceCommand(commandName, out commandTypeInfo); if (!isLocalCommandFound) { throw new WindServiceBusLocalServiceNotFoundException(commandName.FullServiceUniqueName); } //从本地容器找 IServiceCommandHandlerFactory handlerFactory = commandTypeInfo.CommandHandlerFactory; IServiceCommandHandler commandHandler = handlerFactory.CreateHandler(); //服务实例(命令处理者) try { Type commandHandlerType = typeof(IServiceCommandHandler <,>).MakeGenericType(commandType, commandResultType); MethodInfo method = commandHandlerType.GetMethod("HandlerCommand", new[] { commandType }); var result = (IServiceCommandResult)method.Invoke(commandHandler, new object[] { commandData }); return(result); } catch (Exception ex) { //TODO: 异常处理 if (ex.InnerException != null) { throw ex.InnerException; } throw ex; } finally { //清理服务 handlerFactory.ReleaseHandler(commandHandler); } }