public MoviesViewModel Handle(UpdateMoviesCommand message) { try { string validateModel = message == null ? "Command model is null, bad request" : message.ValidateModel(); if (string.IsNullOrEmpty(validateModel)) { var commandService = new ServiceCommand(); var movies = commandService.UpdateMovies(message.Id, message.Title, (int)message.RunningTime, message.ReleaseDate, (bool)message.IsDeleted, message.Rating, message.Discription, (int)message.BookingId); commandService.SaveChanges(); return(new MoviesViewModel { Id = movies.Id, Title = movies.Title, RunningTime = (int)movies.RunningTime, ReleaseDate = (System.DateTime)movies.ReleaseDate, IsDeleted = (bool)movies.IsDeleted, Rating = movies.Rating, Discription = movies.Discription, BookingId = movies.BookingId }); } throw new System.Exception(validateModel); } catch (System.Exception exc) { var log = new ExceptionLog().Log(exc, message); throw exc; } }
public MoviesViewModel Handle(GetMoviesById message) { try { string validateModel = message == null ? "Command model is null, bad request" : message.ValidateModel(); if (string.IsNullOrEmpty(validateModel)) { var ServiceCommand = new ServiceCommand(); var Movie = ServiceCommand.CreateMovies(message.Id, message.Title, (int)message.RunningTime, message.ReleaseDate, (bool)message.IsDeleted, message.Rating, message.Discription, (int)message.BookingId); ServiceCommand.SaveChanges(); return(new MoviesViewModel { Id = message.Id, Title = message.Title, RunningTime = message.RunningTime, ReleaseDate = message.ReleaseDate, IsDeleted = message.IsDeleted, Rating = message.Rating, Discription = message.Discription, BookingId = message.BookingId }); } throw new System.Exception(validateModel); } catch (System.Exception exc) { throw exc; } }
public bool SendByteResult(byte[] bytResult) { byte[] temp = CompressHelper.DeCompress(EnumCompressType.MemCompress, bytResult); string result = ConvertUtility.CodingToString(temp, 2); //result = result.Replace("\n", "\r\n"); if (string.IsNullOrEmpty(result)) { return(false); } ServiceCommand command = new ServiceCommand(); command.CommandStringToClass(result, false); if (command == null || string.IsNullOrEmpty(command.Guid)) { return(false); } return (Singleton <ResultCacheManager <string> > .Instance.AddResult(command.Guid, command.EntityXmlContent)); }
/// <summary> /// 服务执行入口 /// </summary> /// <param name="serviceData">服务传递的数据</param> /// <returns></returns> public void Execute(object serviceData) { ServiceData data = serviceData as ServiceData; if (data == null) { return; } ServiceCommand baseCommand = data.Command; RequestEntity entity = baseCommand.Entity; ResponseEntity responseEntity = new ResponseEntity(); responseEntity.RequestId = entity.RequestId; responseEntity.UserId = entity.UserId; responseEntity.CompressType = (int)EnumCompressType.None; responseEntity.EncyptionType = (int)EnumEncyptionType.None; responseEntity.ResponseStatus = (int)EnumResponseState.Success; m_Logger.Info("NoneService Executed Begin:" + baseCommand.Guid); Thread.Sleep(2000); m_Logger.Info("NoneService Executed End:" + baseCommand.Guid); Singleton <ResultCacheManager> .Instance.AddResult(baseCommand.Guid, responseEntity); }
public ServiceCommand ConvertServiceCommand(CommandAttribute command) { var result = new ServiceCommand(); if (command != null) { result = new ServiceCommand { CircuitBreakerForceOpen = command.CircuitBreakerForceOpen, ExecutionTimeoutInMilliseconds = command.ExecutionTimeoutInMilliseconds, FailoverCluster = command.FailoverCluster, Injection = command.Injection, ShuntStrategy = command.ShuntStrategy, RequestCacheEnabled = command.RequestCacheEnabled, Strategy = command.Strategy, InjectionNamespaces = command.InjectionNamespaces, BreakeErrorThresholdPercentage = command.BreakeErrorThresholdPercentage, BreakerForceClosed = command.BreakerForceClosed, BreakerRequestVolumeThreshold = command.BreakerRequestVolumeThreshold, BreakeSleepWindowInMilliseconds = command.BreakeSleepWindowInMilliseconds, MaxConcurrentRequests = command.MaxConcurrentRequests }; } return(result); }
/// <summary> /// 消息处理 /// </summary> /// <param name="m">消息</param> protected override void DefWndProc(ref Message m) { if (m.Msg == WM_COPYDATA) { try { COPYDATASTRUCT mystr = new COPYDATASTRUCT(); mystr = (COPYDATASTRUCT)Marshal.PtrToStructure(m.LParam, typeof(COPYDATASTRUCT)); if (mystr.cbData > 0) { int nLength = mystr.cbData / 2; string str = Marshal.PtrToStringUni(mystr.lpData, nLength); if (str.Length > nLength) { str = str.Substring(0, nLength); } ServiceCommand requestMessage = new ServiceCommand(); requestMessage.CommandStringToClass(str); ReceiveMessage(requestMessage); } } catch (Exception ex) { m_Logger.Fatal(this.GetType().Name, ex); } } else { base.DefWndProc(ref m); } }
/// <summary> /// 发送消息 /// </summary> /// <param name="message">消息</param> public void SendMessage(ServiceCommand message) { try { m_Logger.Debug("开始发送的消息。"); int WINDOW_HANDLER = 0; message.SendId = m_HostID; string content = message.ClassToCommandString(); m_Logger.Debug("发送的消息为:" + content); m_Logger.Debug("目标窗体ID:" + message.ReceiveId); WINDOW_HANDLER = FindWindow(null, message.ReceiveId); m_Logger.Debug("目标窗体句柄:" + WINDOW_HANDLER); if (WINDOW_HANDLER != 0) { IntPtr ptr = Marshal.StringToHGlobalUni(content); COPYDATASTRUCT mystr = new COPYDATASTRUCT(); mystr.dwData = (IntPtr)59; mystr.cbData = content.Length * 2; mystr.lpData = ptr; SendMessage(WINDOW_HANDLER, WM_COPYDATA, 0, ref mystr); Marshal.FreeHGlobal(ptr); } m_Logger.Debug("发送的消息结束。"); } catch (Exception ex) { m_Logger.Fatal(this.GetType().Name, ex); } }
/// <summary> /// 发送队列中的消息 /// </summary> protected void QueueSend() { while (m_IsSend) { if (m_SendQueue.IsEmpty) { Thread.Sleep(50); continue; } ServiceCommand msg = null; if (m_SendQueue.TryPeek(out msg)) { if (!m_PipeClient.IsConnected) { m_PipeClient.Connect(); } using (StreamWriter sw = new StreamWriter(m_PipeClient)) { sw.AutoFlush = true; sw.WriteLine(msg.ClassToCommandString()); } m_SendQueue.TryDequeue(out msg); } Thread.Sleep(50); } }
/// <summary> /// 接收队列中的消息 /// </summary> protected void QueueReceive() { m_PipeServer.WaitForConnection(); while (m_IsReceived) { if (!m_PipeServer.IsConnected) { Thread.Sleep(50); continue; } ServiceCommand msg = new ServiceCommand(); using (StreamReader sr = new StreamReader(m_PipeServer)) { msg.CommandStringToClass(sr.ReadLine()); } if (msg == null || string.IsNullOrEmpty(msg.Guid)) { continue; } m_ReceiveCommandCaches.AddResult(msg.Guid, msg); if (MessageReceived != null) { // 事件不为为空时 if (MessageReceived != null) { MessageReceived(msg); } } Thread.Sleep(50); } }
/// <summary> /// 状态回调 /// </summary> /// <param name="rs">验证结果</param> private void Received(ServiceCommand rs) { if (rs != null) { m_ReceiveQueue.Enqueue(rs); } }
public void TryDeserializeFromJsonString_should_correctly_deserialize_a_RegistryReadStringValueCommand() { string jsonString = $@" {{ {ParamName.CommandName}: ""{ServiceCommandName.RegistryReadStringValue}"", {ParamName.RegistryBaseKey}: ""{RegistryBaseKey.CurrentUser}"", {ParamName.RegistryKey}: ""Key"", {ParamName.RegistryValueName}: ""ValueName"", {ParamName.RegistryDefaultValue}: ""Value"", }}"; ServiceCommand.TryDeserializeFromJsonString( jsonString, out IServiceCommand command, out IServiceCommandResponse errorResponse) .Should() .BeTrue(); command.Should().BeOfType <RegistryReadStringValueCommand>(); errorResponse.Should().BeNull(); var typedCommand = (RegistryReadStringValueCommand)command; typedCommand.BaseKey.Should().Be(RegistryBaseKey.CurrentUser); typedCommand.Key.Should().Be("Key"); typedCommand.ValueName.Should().Be("ValueName"); typedCommand.DefaultValue.Should().Be("Value"); }
/// <summary> /// 处理接收的数据 /// </summary> void DealReceive() { while (m_IsReceived) { if (m_ReceiveQueue.IsEmpty) { Thread.Sleep(50); continue; } string message = null; m_Logger.Debug("开始处理接收的数据。"); if (m_ReceiveQueue.TryDequeue(out message)) { ServiceCommand requestMessage = new ServiceCommand(); requestMessage.CommandStringToClass(message); m_Logger.Debug("解析接收数据成功。"); if (MessageReceived != null && requestMessage != null && !string.IsNullOrEmpty(requestMessage.Guid)) { MessageReceived(requestMessage); } } m_Logger.Debug("处理接收的数据结束。"); Thread.Sleep(50); } }
/// <summary> /// Method used to start a ProcessMessage blocking method call /// If this is a cached message then retreive the data from the response data from the cache /// <param name="xmlClientMessage">PaymentItem client message</param> /// <param name="xmlClientMessage"></param> /// <returns>PaymentItems xml string response</returns> public string ProcessMessageBlocking(string xmlClientMessage, ServerStores serverStores, getUserIdDelegate getUserIdCall) { string response = ""; try { PaymentItemsProcessClientMessage clientMessage = new PaymentItemsProcessClientMessage(); ServiceCommand serviceCommand = (ServiceCommand)clientMessage.ProcessMessage(xmlClientMessage, getUserIdCall); if (clientMessage.IsCachedMessage((PaymentCommand)serviceCommand, serverStores)) { response = clientMessage.GetCachedStoreData((PaymentCommand)serviceCommand, serverStores); } else { response = InvokeServiceBlocking(serviceCommand); } } catch (Exception ex) { response = String.Format("<Error><Message>{0}</Message></Error>", ex); mLogger.Error(String.Format("Error ProcessMessageBlocking: {0}", response)); } return(response); }
/// <summary> /// Invokes the remote PaymentItems ProcessMessage service call /// </summary> /// <param name="serviceCommand">PaymentItemCommand</param> /// <returns>xml string response from the PaymentItems service call</returns> protected override string InvokeServiceCommandHandler(ServiceCommand serviceCommand) { ServiceCommandSerializer serializer = new ServiceCommandSerializer(); string xmlPaymentItemsMessage = serializer.SerializeCommandData(serviceCommand, typeof(PaymentCommand)); return(mPaymentItemProcess.ProcessMessage(xmlPaymentItemsMessage)); }
/// <summary> /// 获取计算结果 /// </summary> /// <param name="command"></param> /// <returns></returns> public ResponseEntity GetResponseEntity(ServiceCommand command) { // 获取计算结果 ResponseEntity responseEntity = null; string resultId = command.Guid; RequestEntity requestEntity = command.Entity as RequestEntity; bool isTimeOut = false; ServiceCommand result = m_ReceiveCommandCaches.GetResponseEntity(resultId, requestEntity.TimeOut, out isTimeOut); // 超时 if (isTimeOut) { responseEntity = new ResponseEntity(); responseEntity.RequestId = requestEntity.RequestId; responseEntity.UserId = requestEntity.UserId; responseEntity.CompressType = (int)EnumCompressType.None; responseEntity.EncyptionType = (int)EnumEncyptionType.None; ServiceUtility.SetResponseStatus(responseEntity, EnumResponseState.TimeOut); } else { responseEntity = result.Entity as ResponseEntity; } return(responseEntity); }
/// <summary> /// Method used to start a ProcessMessage async method call /// This method processes PaymentItems messages /// If this is a cached message then retreive the data from the response data from the cache /// </summary> /// <param name="xmlClientMessage">PaymentItem client message</param> /// <param name="sender">List of session GUID's to send the response to</param> /// <param name="callback">Callback that is called on response from service</param> /// <returns>blank if no error else the error message</returns> public string ProcessMessageAsync(string xmlClientMessage, System.Action <string> callback, ServerStores serverStores, getUserIdDelegate getUserIdCall) { string response = ""; try { PaymentItemsProcessClientMessage clientMessage = new PaymentItemsProcessClientMessage(); ServiceCommand serviceCommand = (ServiceCommand)clientMessage.ProcessMessage(xmlClientMessage, getUserIdCall); if (clientMessage.IsCachedMessage((PaymentCommand)serviceCommand, serverStores)) { response = clientMessage.GetCachedStoreData((PaymentCommand)serviceCommand, serverStores); clientMessage.PaymentItemsReturn(response, callback); } else if (clientMessage.IsDoNothing((PaymentCommand)serviceCommand)) { response = clientMessage.createDoNothingResponse((PaymentCommand)serviceCommand); clientMessage.PaymentItemsReturn(response, callback); } else { InvokeServiceAsync(serviceCommand, callback); } } catch (Exception ex) { response = String.Format("<Error><Message>{0}</Message></Error>", ex); mLogger.Error(String.Format("Error ProcessMessageAsync: {0}", response)); } return(response); }
/// <summary> /// 发送队列中的消息 /// </summary> protected void QueueSend() { while (m_IsSend) { if (m_SendQueue.IsEmpty) { Thread.Sleep(50); continue; } m_Logger.Debug("开始发送请求"); ServiceCommand msg = null; if (m_SendQueue.TryPeek(out msg)) { if (!m_MSMQ.CanWrite) { continue; } m_MSMQ.Send(msg.ClassToCommandString()); m_SendQueue.TryDequeue(out msg); } m_Logger.Debug("发送请求结束"); Thread.Sleep(50); } }
public static bool RemoveFromFavorites(this SupplementCycleDefinitionDTO definition) { if (!CanRemoveFromFavorites(definition)) { return(false); } //ServiceManager.WorkoutPlanFavoritesOperation(plan, FavoriteOperation.Remove); ServiceCommand command = new ServiceCommand(() => { try { var param = new SupplementsCycleDefinitionOperationParam(); param.SupplementsCycleDefinitionId = definition.GlobalId; param.Operation = SupplementsCycleDefinitionOperation.RemoveFromFavorites; ServiceManager.SupplementsCycleDefinitionOperation(param); } catch (ObjectIsNotFavoriteException) { } catch { SupplementsCycleDefinitionsReposidory.Instance.Add(definition); throw; } }); ServicePool.Add(command); SupplementsCycleDefinitionsReposidory.Instance.Remove(definition.GlobalId); return(true); }
public void TryDeserializeValueSet_should_correctly_deserialize_a_RegistryWriteIntValueCommand() { var valueSet = new Dictionary <string, object> { [ParamName.CommandName.ToString()] = ServiceCommandName.RegistryWriteIntValue.ToString(), [ParamName.RegistryBaseKey.ToString()] = RegistryBaseKey.CurrentUser.ToString(), [ParamName.RegistryKey.ToString()] = "Key", [ParamName.RegistryValueName.ToString()] = "ValueName", [ParamName.RegistryValue.ToString()] = 123 }; ServiceCommand.TryDeserializeFromValueSet( valueSet, out IServiceCommand command, out IServiceCommandResponse errorResponse) .Should() .BeTrue(); command.Should().BeOfType <RegistryWriteIntValueCommand>(); errorResponse.Should().BeNull(); var typedCommand = (RegistryWriteIntValueCommand)command; typedCommand.BaseKey.Should().Be(RegistryBaseKey.CurrentUser); typedCommand.Key.Should().Be("Key"); typedCommand.ValueName.Should().Be("ValueName"); typedCommand.Value.Should().Be(123); }
/// <summary> /// Manage the service /// </summary> public bool ControlService(ServiceApp serviceApp, ServiceCommand command) { try { string batchFileName = Path.Combine(Settings.Directory, DirectoryBuilder.GetDirectory(serviceApp), GetServiceBatchFile(command)); if (File.Exists(batchFileName)) { Process.Start(new ProcessStartInfo() { FileName = batchFileName, UseShellExecute = false }); return(true); } else { log.WriteError(string.Format( Localization.UseRussian ? "Не найден файл для управления службой {0}" : "File {0} for service control not found", batchFileName)); return(false); } } catch (Exception ex) { log.WriteException(ex, Localization.UseRussian ? "Ошибка при управлении службой" : "Error controlling service"); return(false); } }
/// <summary> /// Invoke Service Blocking /// </summary> /// <param name="serviceCommand">The Service Command</param> /// <returns>The xml string response</returns> public string InvokeServiceBlocking(ServiceCommand serviceCommand) { string response = ""; response = InvokeServiceCommand((ServiceCommand)serviceCommand); return(response); }
/// <summary> /// Sends the command to the service. /// </summary> public bool ControlService(ServiceApp serviceApp, ServiceCommand command) { RestoreConnection(); bool result = client.ControlService(sessionID, serviceApp, command); RegisterActivity(); return(result); }
public void Service_Execute_ReturnsEmpty() { var console = new TestConsole(_output, "userPassword"); var command = new ServiceCommand(_helpContextService.Object, console, LoggerMock.GetLogger <ServiceCommand>().Object); var resultMessage = command.Execute(); Assert.Equal("", resultMessage); }
/// <summary> /// 根据指令格式获取执行的服务 /// </summary> /// <param name="commandInfo"></param> /// <returns></returns> public IService GetService(ServiceCommand commandInfo) { ServiceUtility.ExportLog(m_Logger, LogExport, "获取服务,服务名称为:" + commandInfo.ServiceFullName); try { IService iService = null; if (commandInfo == null || string.IsNullOrEmpty(commandInfo.ServiceFullName)) { return(null); } if (m_DicServices.ContainsKey(commandInfo.ServiceFullName)) { m_DicServices.TryGetValue(commandInfo.ServiceFullName, out iService); } else { string runDirecory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Services"); string dllFilePath = Path.Combine(runDirecory, commandInfo.ServiceDLLName); m_Logger.Debug("服务DLL路径:" + dllFilePath); if (!File.Exists(dllFilePath)) { m_Logger.Debug("服务DLL路径不存在。"); return(null); } Assembly assem = Assembly.LoadFile(dllFilePath); if (assem == null) { return(null); } iService = assem.CreateInstance(commandInfo.ServiceFullName) as IService; if (iService == null) { return(null); } // 添加服务 AddService(iService); } ServiceUtility.ExportLog(m_Logger, LogExport, "获取服务结束。"); return(iService); } catch (Exception ex) { m_Logger.Debug("获取服务结束异常。"); m_Logger.Fatal(string.Concat("GetService 错误: ", ex.Message)); m_Logger.Fatal(string.Concat("GetService 错误: ", ex.StackTrace)); } m_Logger.Debug("没有获取到服务。"); return(null); }
/// <summary> /// 状态回调 /// </summary> /// <param name="rs">验证结果</param> private void Received(ServiceCommand rs) { if (rs != null) { m_ReceiveCommandCaches.AddResult(rs.Guid, rs); //m_ReceiveQueue.Enqueue(rs); m_SendCommandCaches.RemoveResult(rs.Guid); } }
/// <summary> /// 接收到消息 /// </summary> /// <param name="message"></param> void Instance_MessageReceived(ServiceCommand message) { if (message == null || string.IsNullOrEmpty(message.Guid)) { return; } Singleton <ResultCacheManager <string> > .Instance.AddResult(message.Guid, message.EntityXmlContent); }
public void ServiceCommand_Constructor_With_Sync_Method_Args_Contains_Correct_Errors_On_Failure() { var command = new ServiceCommand <Person>( executeMethod: () => new Person(), getBusinessRulesMethod: () => new[] { new FalseRule1() } ); command.Execute().Errors.First().ErrorMessage.ShouldBe("FalseRule1 failed validation"); }
public TunableButton() { Click += (sender, args) => { ServiceCommand?.Invoke(this, new CommandEventArgs { Command = _command }); }; }
public async Task ServiceCommand_Constructor_With_Async_Method_Args_Contains_Correct_Errors_On_Failure() { var command = new ServiceCommand <Person>( executeAsyncMethod: () => Task.Run(() => new Person()), getBusinessRulesAsyncMethod: () => Task.Run <IEnumerable <IRule> >(() => new [] { new FalseRule1() }) ); var result = await command.ExecuteAsync(); result.Errors.First().ErrorMessage.ShouldBe("FalseRule1 failed validation"); }
public void AddsSubCommands(Type commandType) { var command = new ServiceCommand(); var subCommands = command.Children.Where(x => x.GetType() == commandType); var subCommand = Assert.Single(subCommands); Assert.NotNull(subCommand); }
public void Execute(ServiceCommand command) { ServiceController sc = new ServiceController(serviceName); switch (command) { case ServiceCommand.Start: sc.Start(); break; case ServiceCommand.Stop: sc.Stop(); break; case ServiceCommand.Restart: RestartService(sc, 20000); break; default: throw new ArgumentException("Invalid command", "command"); } }
public void ShowPairingKeyOnTv() { ServiceConnectionState = ConnectionState.Connecting; var responseListener = new ResponseListener ( loadEventArg => { if (Listener != null) Listener.OnPairingRequired(this, PairingType.PIN_CODE, null); }, serviceCommandError => { ServiceConnectionState = ConnectionState.Initial; if (Listener != null) Listener.OnConnectionFailure(this, new Exception(serviceCommandError.ToString())); } ); var requestUrl = GetUdapRequestUrl(UdapPathPairing); var ps = new Dictionary<string, string> { { "name", "showKey" } }; string httpMessage = GetUdapMessageBody(UdapApiPairing, ps); var command = new ServiceCommand(this, requestUrl, httpMessage, responseListener); command.Send(); }
public void SetChannel(ChannelInfo channelInfo, ResponseListener listener) { var responseListener = new ResponseListener ( loadEventArg => { //((ConnectSdk.Windows.Service.Capability.Listeners.LoadEventArgs)(o)).Load.payload var loa = loadEventArg as LoadEventArgs; if (loa != null) { var channelList = loa.Load.GetPayload() as List<ChannelInfo>; if (channelList != null) { var requestUrl = GetUdapRequestUrl(UdapPathCommand); var ps = new Dictionary<string, string>(); foreach (var ch in channelList) { //var rawData = ch.RawData; var major = channelInfo.MajorNumber; var minor = channelInfo.MinorNumber; var majorNumber = ch.MajorNumber; var minorNumber = ch.MinorNumber; if (major != majorNumber || minor != minorNumber) continue; ps.Add("name", "HandleChannelChange"); ps.Add("major", major.ToString()); ps.Add("minor", minor.ToString()); break; } var httpMessage = GetUdapMessageBody(UdapApiCommand, ps); var request = new ServiceCommand(this, requestUrl, httpMessage, listener); request.Send(); } else { Util.PostError(listener, new ServiceCommandError(500, "Could not retrieve channel list")); } } else { Util.PostError(listener, new ServiceCommandError(500, "Could not retrieve channel list")); } }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); GetChannelList(responseListener); }
public override void SendPairingKey(string pairingKey) { ServiceConnectionState = ConnectionState.Pairing; if (!(ServiceConfig is NetcastTvServiceConfig)) { ServiceConfig = new NetcastTvServiceConfig(ServiceConfig.ServiceUuid); } var responseListener = new ResponseListener ( loadEventArg => { ServiceConnectionState = ConnectionState.Paired; ((NetcastTvServiceConfig)ServiceConfig).PairingKey = pairingKey; ConnectSuccess(); }, serviceCommandError => { ServiceConnectionState = ConnectionState.Initial; if (Listener != null) Listener.OnConnectionFailure(this, new Exception(serviceCommandError.ToString())); } ); var requestUrl = GetUdapRequestUrl(UdapPathPairing); var ps = new Dictionary<string, string> { {"name", "hello"}, {"value", pairingKey}, {"port", ServiceDescription.Port.ToString()} }; var httpMessage = GetUdapMessageBody(UdapApiPairing, ps); var command = new ServiceCommand(this, requestUrl, httpMessage, responseListener); command.Send(); }
public override void SendCommand(ServiceCommand mCommand) { var t = new Task(() => { var command = mCommand; var payload = command.Payload; if (command.HttpMethod == "request") command.HttpMethod = HttpMethod.Get.ToString(); var request = command.GetRequest(); request.Headers.Add(HttpMessage.USER_AGENT, HttpMessage.UDAP_USER_AGENT); if (payload != null && command.HttpMethod.Equals(ServiceCommand.TypePost)) { request.Method = HttpMethod.Post; request.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(payload.ToString()))); request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/xml") { CharSet = "utf-8" }; } var res = httpClient.SendAsync(request).Result; if (res.IsSuccessStatusCode) { Util.PostSuccess(command.ResponseListenerValue, res); } else { Util.PostError(command.ResponseListenerValue, ServiceCommandError.GetError((int)res.StatusCode)); } }); t.RunSynchronously(); }
private void GetVolumeStatus(ResponseListener listener) { var responseListener = new ResponseListener ( loadEventArg => { var strObj = (new StreamReader( (((HttpResponseMessage)((LoadEventArgs)loadEventArg).Load.GetPayload()).Content.ReadAsStreamAsync() .Result))) .ReadToEnd(); var reader = Util.GenerateStreamFromstring(strObj); var xmlReader = XmlReader.Create(reader); var isMute = false; var volume = 0; while (xmlReader.Read()) { if (xmlReader.Name == "mute") isMute = bool.Parse(xmlReader.ReadElementContentAsString()); if (xmlReader.Name == "level") volume = int.Parse(xmlReader.ReadElementContentAsString()); } Util.PostSuccess(listener, new VolumeStatus(isMute, volume)); }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); var requestUrl = GetUdapRequestUrl(UdapPathData, TargetVolumeInfo); var request = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet }; request.Send(); }
private void GetApplications(int type, int number, ResponseListener listener) { var responseListener = new ResponseListener ( loadEventArg => { var lea = loadEventArg as LoadEventArgs; if (lea == null) return; var load = lea.Load.GetPayload() as HttpResponseMessage; if (load == null) return; var strObj = load.Content.ReadAsStringAsync().Result; var appList = new List<AppInfo>(); var reader = Util.GenerateStreamFromstring(strObj); var xmlReader = XmlReader.Create(reader); while (xmlReader.Read()) { if (xmlReader.Name.Equals("data", StringComparison.OrdinalIgnoreCase)) appList.Add(new AppInfo("")); if (xmlReader.Name.Equals("auid", StringComparison.OrdinalIgnoreCase)) appList[appList.Count - 1].Id = xmlReader.ReadElementContentAsString(); if (xmlReader.Name.Equals("name", StringComparison.OrdinalIgnoreCase)) appList[appList.Count - 1].Name = xmlReader.ReadElementContentAsString(); } appList = (from a in appList where !string.IsNullOrEmpty(a.Name) select a).ToList(); if (listener != null) { Util.PostSuccess(listener, appList); } }, serviceCommandError => { } ); var requestUrl = GetUdapRequestUrl(UdapPathData, TargetApplistGet, type.ToString(), "0", number.ToString()); var command = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet }; command.Send(); }
private void HandleKeyboardInput(string state, string buffer) { var responseListener = new ResponseListener(); var requestUrl = GetUdapRequestUrl(UdapPathEvent); var ps = new Dictionary<string, string> { { "name", "TextEdited" }, { "state", state }, { "value", buffer } }; var httpMessage = GetUdapMessageBody(UdapApiEvent, ps); var request = new ServiceCommand(this, requestUrl, httpMessage, responseListener); request.Send(); }
private void MoveMouse() { var requestUrl = GetUdapRequestUrl(UdapPathCommand); var x = (int)mMouseDistance.X; var y = (int)mMouseDistance.Y; var ps = new Dictionary<string, string> { {"name", "HandleTouchMove"}, {"x", x.ToString()}, {"y", y.ToString()} }; mMouseDistance.X = mMouseDistance.Y = 0; var mouseService = this; var responseListener = new ResponseListener ( loadEventArg => { if (mMouseDistance.X > 0 || mMouseDistance.Y > 0) mouseService.MoveMouse(); else mMouseIsMoving = false; }, serviceCommandError => { Logger.Current.AddMessage("Netcast TV's mouse move has failed"); mMouseIsMoving = false; } ); var httpMessage = GetUdapMessageBody(UdapApiCommand, ps); var request = new ServiceCommand(this, requestUrl, httpMessage, responseListener); request.Send(); }
private void SetMouseCursorVisible(bool visible, ResponseListener listener) { var requestUrl = GetUdapRequestUrl(UdapPathEvent); var ps = new Dictionary<string, string> { {"name", "CursorVisible"}, {"value", visible ? "true" : "false"}, {"mode", "auto"} }; var httpMessage = GetUdapMessageBody(UdapApiEvent, ps); var request = new ServiceCommand(this, requestUrl, httpMessage, listener); request.Send(); }
public void GetApplication(string appName, ResponseListener listener) { var responseListener = new ResponseListener ( loadEventArg => { var strObj = LoadEventArgs.GetValue<string>(loadEventArg); var appId = new AppInfo(Util.DecToHex(strObj)); if (!string.IsNullOrEmpty(strObj)) { Util.PostSuccess(listener, appId); } }, serviceCommandError => { if (listener != null) Util.PostError(listener, serviceCommandError); } ); var uri = UdapPathApptoappData + appName; var requestUrl = GetUdapRequestUrl(uri); var command = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet }; command.Send(); }
public void GetSystemInfo(ResponseListener listener) { const string uri = "ssap://api/getServiceList"; var responseListener = new ResponseListener ( loadEventArg => { var loadEventArgs = loadEventArg as LoadEventArgs; if (loadEventArgs == null) return; var jsonObj = (JsonObject) (loadEventArgs.Load.GetPayload()); if (jsonObj.ContainsKey("features")) { listener.OnSuccess(new ServiceCommandError(0, jsonObj.GetNamedArray("features"))); } }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); var request = new ServiceCommand(this, uri, null, responseListener); request.Send(); }
public void GetExternalInputList(ResponseListener listener) { const string uri = "ssap://tv/getExternalInputList"; var responseListener = new ResponseListener ( loadEventArg => { var res = LoadEventArgs.GetValue<JsonObject>(loadEventArg); if (res != null) { var devices = res.GetNamedArray("devices"); Util.PostSuccess(listener, devices); } }, serviceCommandError => Util.PostError(listener, serviceCommandError)); var request = new ServiceCommand(this, uri, null, responseListener); request.Send(); }
private void EndPairing(ResponseListener listener) { var requestUrl = GetUdapRequestUrl(UdapPathPairing); var ps = new Dictionary<string, string> { {"name", "byebye"}, {"port", ServiceDescription.Port.ToString()} }; var httpMessage = GetUdapMessageBody(UdapApiPairing, ps); var command = new ServiceCommand(this, requestUrl, httpMessage, listener); command.Send(); }
public void Click() { if (isMouseConnected) ConnectMouse(); var responseListener = new ResponseListener(); var requestUrl = GetUdapRequestUrl(UdapPathCommand); var ps = new Dictionary<string, string> { { "name", "HandleTouchClick" } }; var httpMessage = GetUdapMessageBody(UdapApiCommand, ps); var request = new ServiceCommand(this, requestUrl, httpMessage, responseListener); request.Send(); }
// TODO add this when user cancel pairing public void RemovePairingKeyOnTv() { var responseListener = new ResponseListener ( loadEventArg => { }, serviceCommandError => { } ); var requestUrl = GetUdapRequestUrl(UdapPathPairing); var ps = new Dictionary<string, string> { { "name", "CancelAuthKeyReq" } }; var httpMessage = GetUdapMessageBody(UdapApiPairing, ps); var command = new ServiceCommand(this, requestUrl, httpMessage, responseListener); command.Send(); }
private void GetTotalNumberOfApplications(int type, ResponseListener listener) { var responseListener = new ResponseListener ( loadEventArg => { var lea = loadEventArg as LoadEventArgs; if (lea == null) return; var load = lea.Load.GetPayload() as HttpResponseMessage; if (load == null) return; var strObj = load.Content.ReadAsStringAsync().Result; JsonObject jsonObject; JsonObject.TryParse(strObj, out jsonObject); //var tarray = jsonObject.GetNamedArray("Channel List", new JsonArray()); var applicationNumber = ParseAppNumberXmlToJson(strObj); Util.PostSuccess(listener, applicationNumber); }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); var requestUrl = GetUdapRequestUrl(UdapPathData, TargetAppnumGet, type.ToString()); var command = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet }; command.Send(); }
public void Scroll(double dx, double dy) { if (isMouseConnected) ConnectMouse(); var responseListener = new ResponseListener(); var requestUrl = GetUdapRequestUrl(UdapPathCommand); var ps = new Dictionary<string, string> { { "name", "HandleTouchWheel" }, { "value", dy > 0 ? "up" : "down" } }; var httpMessage = GetUdapMessageBody(UdapApiCommand, ps); var request = new ServiceCommand(this, requestUrl, httpMessage, responseListener); request.Send(); }
public void CloseApp(LaunchSession launchSession, ResponseListener listener) { var requestUrl = GetUdapRequestUrl(UdapPathApptoappCommand); var ps = new Dictionary<string, string> { { "name", "AppTerminate" }, { "auid", launchSession.AppId } }; if (launchSession.AppName != null) ps.Add("appname", HttpMessage.Encode(launchSession.AppName)); var httpMessage = GetUdapMessageBody(UdapApiCommand, ps); var command = new ServiceCommand(launchSession.Service, requestUrl, httpMessage, listener); command.Send(); }
public void GetChannelList(ResponseListener listener) { var requestUrl = GetUdapRequestUrl(UdapPathData, TargetChannelList); var responseListener = new ResponseListener ( loadEventArg => { var lea = loadEventArg as LoadEventArgs; if (lea == null) return; var load = lea.Load.GetPayload() as HttpResponseMessage; if (load == null) return; var strObj = load.Content.ReadAsStringAsync().Result; var ser = new XmlSerializer(typeof(envelope)); var obj = ser.Deserialize(new StringReader(strObj)) as envelope; if (obj != null) { var channels = new List<ChannelInfo>(); for (var i = 0; i < obj.dataList.data.Count(); i++) { channels.Add(new ChannelInfo { Id = obj.dataList.data[i].displayMajor.ToString(), Number = obj.dataList.data[i].displayMajor.ToString(), Name = obj.dataList.data[i].chname.ToString(), MajorNumber = obj.dataList.data[i].displayMajor, MinorNumber = obj.dataList.data[i].displayMinor, }); } Util.PostSuccess(listener, channels); } else { Util.PostError(listener, new ServiceCommandError(0, null)); } }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); var command = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet }; command.Send(); }
private void LaunchApplication(string appName, string auid, string contentId, ResponseListener listener) { var responseListener = new ResponseListener ( loadEventArg => { var launchSession = LaunchSession.LaunchSessionForAppId(auid); launchSession.AppName = appName; launchSession.Service = this; launchSession.SessionType = LaunchSessionType.App; Util.PostSuccess(listener, launchSession); }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); var requestUrl = GetUdapRequestUrl(UdapPathApptoappCommand); var ps = new Dictionary<string, string> { { "name", "AppExecute" }, { "auid", auid } }; if (appName != null) { ps.Add("appname", appName); } if (contentId != null) { ps.Add("contentid", contentId); } var httpMessage = GetUdapMessageBody(UdapApiCommand, ps); var request = new ServiceCommand(this, requestUrl, httpMessage, responseListener); request.Send(); }
private void ConnectMouse(ResponseListener listener) { const string uri = "ssap://com.webos.service.networkinput/getPointerInputSocket"; var request = new ServiceCommand(this, uri, null, listener); request.Send(); }
private void SendVirtualKeyCode(int keycode, ResponseListener listener) { var responseListener = new ResponseListener ( loadEventArg => { var requestUrl = GetUdapRequestUrl(UdapPathCommand); var httpMessage = GetHttpMessageForHandleKeyInput(keycode); var request = new ServiceCommand(this, requestUrl, httpMessage, listener); request.Send(); }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); SetMouseCursorVisible(false, responseListener); }
private void DisplayMedia(JsonObject ps, ResponseListener listener) { const string uri = "ssap://media.viewer/open"; var responseListener = new ResponseListener ( loadEventArg => { var obj = (JsonObject)(((LoadEventArgs)loadEventArg).Load.GetPayload()); LaunchSession launchSession = LaunchSession.LaunchSessionForAppId(obj.GetNamedString("id")); launchSession.Service = this; launchSession.SessionId = obj.GetNamedString("sessionId"); launchSession.SessionType = LaunchSessionType.Media; Util.PostSuccess(listener, new MediaLaunchObject(launchSession, this)); }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); var request = new ServiceCommand(this, uri, ps, responseListener); request.Send(); }
public void Get3DEnabled(ResponseListener listener) { var responseListener = new ResponseListener ( loadEventArg => { var strObj = (string)loadEventArg; var upperStr = strObj.ToUpper(); Util.PostSuccess(listener, upperStr.Contains("TRUE")); }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); var requestUrl = GetUdapRequestUrl(UdapPathData, TargetIs_3D); var request = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet }; request.Send(); }
private void SendToast(JsonObject payload, ResponseListener listener) { if (!payload.ContainsKey("iconData")) { //todo: find a way to get the icon and add it to the request //Context context = DiscoveryManager.getInstance().getContext(); //try //{ // Drawable drawable = context.getPackageManager().getApplicationIcon(context.getPackageName()); // if (drawable != null) // { // BitmapDrawable bitDw = ((BitmapDrawable)drawable); // Bitmap bitmap = bitDw.getBitmap(); // ByteArrayOutputStream stream = new ByteArrayOutputStream(); // bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // byte[] bitmapByte = stream.toByteArray(); // bitmapByte = Base64.encode(bitmapByte, Base64.NO_WRAP); // String bitmapData = new String(bitmapByte); // payload.put("iconData", bitmapData); // payload.put("iconExtension", "png"); // } //} //catch (NameNotFoundException e) //{ // e.printStackTrace(); //} //catch (JSONException e) //{ // e.printStackTrace(); //} } const string uri = "palm://system.notifications/createToast"; var request = new ServiceCommand(this, uri, payload, listener); request.Send(); }
public void GetAppState(LaunchSession launchSession, ResponseListener listener) { var requestUrl = string.Format("{0}{1}", GetUdapRequestUrl(UdapPathApptoappData), string.Format("/{0}/status", launchSession.AppId)); var responseListener = new ResponseListener ( loadEventArg => { var response = (string)loadEventArg; AppState appState; if (response.Equals("NONE")) appState = new AppState(false, false); else if (response.Equals("LOAD")) appState = new AppState(false, true); else if (response.Equals("RUN_NF")) appState = new AppState(true, false); else if (response.Equals("TERM")) appState = new AppState(false, true); else appState = new AppState(false, false); Util.PostSuccess(listener, appState); }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); var command = new ServiceCommand(this, requestUrl, null, responseListener) { HttpMethod = ServiceCommand.TypeGet }; command.Send(); }
public void FastForward(ResponseListener listener) { const string uri = "ssap://media.controls/fastForward"; var request = new ServiceCommand(this, uri, null, listener); request.Send(); }
public void GetCurrentChannel(ResponseListener listener) { var requestUrl = GetUdapRequestUrl(UdapPathData, TargetCurrentChannel); var responseListener = new ResponseListener ( loadEventArg => { //TODO: fix this //var strObj = (string)o; //SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); //InputStream stream = new ByteArrayInputStream(strObj.getBytes("UTF-8")); //SAXParser saxParser = saxParserFactory.newSAXParser(); //NetcastChannelParser parser = new NetcastChannelParser(); //saxParser.parse(stream, parser); //JSONArray channelArray = parser.getJSONChannelArray(); //if ( channelArrayLength > 0 ) { // JsonObject rawData = (JsonObject) channelArray.get(0); // ChannelInfo channel = NetcastChannelParser.parseRawChannelData(rawData); // Util.PostSuccess(listener, channel); //} }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); var request = new ServiceCommand(this, requestUrl, null, responseListener); request.Send(); }
public void GetAppList(ResponseListener listener) { const string uri = "ssap://com.webos.applicationManager/listApps"; var responseListener = new ResponseListener ( loadEventArg => { try { var jsonObj = (JsonObject)(((LoadEventArgs)loadEventArg).Load.GetPayload()); var apps = jsonObj.GetNamedArray("apps"); var appList = (from t in apps select t.GetObject() into appObj where appObj != null select new AppInfo(appObj.GetNamedString("id")) { Name = appObj.GetNamedString("title"), Url = appObj.GetNamedString("icon"), RawData = appObj }).ToList(); Util.PostSuccess(listener, appList); } catch { } }, serviceCommandError => Util.PostError(listener, serviceCommandError) ); var request = new ServiceCommand(this, uri, null, responseListener); request.Send(); }