public MainResponse GetAllStates() { var states = _stateRepository.GetAll(x => x.IsDeleted == false && x.IsActive == true).OrderBy(x => x.Name); var stateResponse = _mapper.Map <List <State> >(states); StateResponse response = new StateResponse(); response.State = stateResponse; _mainResponse.StateResponse = response; _mainResponse.Success = true; return(_mainResponse); }
public void TestValidStateResponse(string response, bool motorRunning, CoverState covertState, bool lightOn) { var sut = new StateResponse { DeviceResponse = response }; sut.Ttl.Should().Be(0); sut.MotorRunning.Should().Be(motorRunning); sut.CoverState.Should().Be(covertState); sut.LightOn.Should().Be(lightOn); }
public GetStatisticsResponse GetStatistics() { StateResponse stateResponse = RequestState(); var statisticsResponse = new GetStatisticsResponse() { ManMinutesPlayed = stateResponse.ManMinutesPlayed, RunningSinceUtc = stateResponse.RunningSinceUtc }; return(statisticsResponse); }
internal static DreamScreenResponse Create(Message message) { DreamScreenResponse response = new AcknowledgementResponse(message); switch (message.Type) { case MessageType.Brightness: response = new BrightnessResponse(message); break; case MessageType.GetSerial: response = new DeviceSerialResponse(message); break; case MessageType.Mode: response = new ModeResponse(message); break; case MessageType.Name: response = new DeviceNameResponse(message); break; case MessageType.AmbientColor: response = new AmbientColorResponse(message); break; case MessageType.AmbientScene: response = new AmbientSceneResponse(message); break; case MessageType.AmbientModeType: response = new AmbientModeResponse(message); break; case MessageType.GroupName: response = new GroupNameResponse(message); break; case MessageType.GroupNumber: response = new GroupNumberResponse(message); break; case MessageType.ColorData: response = new ColorResponse(message); break; case MessageType.DeviceDiscovery: response = new StateResponse(message); break; } return(response); }
private static void ProcessGetCurrentStateRequest() { StateResponse response = new StateResponse { Servers = Program.State.Servers.Values.ToList(), ManMinutesPlayed = (int)Math.Floor(Program.State.Playtime.TotalMinutes), RunningSinceUtc = Program.State.CreatedAtUtc, }; byte[] serializedResponse = ObjectToByteArray(response); socket.SendTo(serializedResponse, webApiEndPoint); }
public async Task Connect(string host, string auth, bool isSecure, string group = null, string code = null) { Hostname = host; Authentification = auth; State = "Verbinde..."; IsActive = true; try { socket = new ClientWebSocket(); socket.Options.AddSubProtocol("chat"); await socket.ConnectAsync(new Uri((isSecure ? "wss://":"ws://") + host), source.Token); int seq = SequenceNumber++; AuthRequest msg = new AuthRequest(auth, seq, group, code); ReceiveTokenSource = new CancellationTokenSource(); ProcessReceivingMessages(); await socket.SendAsync(msg.GetBytes(), WebSocketMessageType.Binary, true, source.Token); IRemoteMessage resp = await WaitForResponse(seq); if (resp is StateResponse) { StateResponse response = (StateResponse)resp; switch (response.Code) { case StateCodes.WrongKey: throw new Exception("Authentifizierung am Server fehlgeschlagen"); case StateCodes.GroupNotFound: throw new Exception("Angegebene Gruppe ist nicht auf dem Server vorhanden"); case StateCodes.WrongGroupKey: throw new Exception("Authentifizierung in der Gruppe fehlgeschlagen"); } } else if (resp is AuthResponse) { AuthResponse response = (AuthResponse)resp; Group = response.Group; State = "Verbunden (" + Group + ")"; } else { throw new Exception("Ungültige Antwort erhalten: " + resp.GetType().ToString()); } } catch (Exception ex) { State = ex.Message; IsActive = false; IsConnected = false; } }
private void StateRequestThread() { while (!_abort) { _stateRequestEvent.WaitOne(); if (_abort) { return; } DateTime startTime = DateTime.Now; try { StateRequest stateRequest = new StateRequest(); stateRequest.HashCode = _hashCode; StateResponse stateResponse = Client.Invoke <StateRequest, StateResponse>(stateRequest); if (!string.IsNullOrEmpty(stateResponse.HashCode)) { _hashCode = stateResponse.HashCode; Logger.IsEnabled = stateResponse.TraceLevel.ToLower() != "off"; _form.Invoke(new Action(() => { _form.RenderState(stateResponse); })); } } catch (ServerFaultException ex) { HandleServerFaultException(ex); _abort = true; } catch (ObjectDisposedException) { } catch (Exception) { TimeSpan processingTime = DateTime.Now - startTime; if (processingTime.TotalMilliseconds < Client.ConnectTimeout) { int sleepTime = Client.ConnectTimeout - (int)processingTime.TotalMilliseconds; Thread.Sleep(sleepTime); } } } }
public async Task <ActionResult <State> > PostBook(StateResponse stateResponse) { stateResponse.Country = await _context.Countries.FirstOrDefaultAsync(d => d.Id == stateResponse.Country.Id); State state = new State { Name = stateResponse.Name, UrlPhoto = stateResponse.UrlPhoto, Country = stateResponse.Country }; _context.States.Add(state); await _context.SaveChangesAsync(); return(CreatedAtAction("GetState", new { id = state.Id }, state)); }
private static StateResponse RequestState() { byte[] payload = Encoding.ASCII.GetBytes($"A"); byte[] response; lock (_locker) { socket.SendTo(payload, webApiListenerEndPoint); response = udpClient.ReceiveAsync().Result.Buffer; } StateResponse stateResponse = (StateResponse)ByteArrayToObject(response); return(stateResponse); }
public void GetsAsyncConversationResult() { var conversation = new CommandConversation(CommandType.Run); ResponseMessage responseMessage = StateResponseBuilder.Build(StateType.Running); ICoreLink coreLink = GenerateCoreLink(responseMessage); Task <StateResponse> futureResponse = coreLink.Request(conversation, WaitMs); StateResponse receivedResponse = ReadResponse(futureResponse); Assert.Equal(StateType.Running, receivedResponse.State); }
public async Task <ActionResult <State> > PostState(StateResponse stateResponse) { var countryTaker = await _context.Countries.FirstOrDefaultAsync(aspdao => aspdao.Id == stateResponse.Country.Id); stateResponse.Country = countryTaker; State state = new State { Name = stateResponse.Name, Flag = stateResponse.Flag, Country = stateResponse.Country }; _context.States.Add(state); await _context.SaveChangesAsync(); return(CreatedAtAction("GetStates", new { id = state.Id }, state)); }
private static string PrepareExpectedResponse(StateEntity stateEntity) { var stateResponse = new StateResponse(stateEntity.Id, stateEntity.RowVersion, stateEntity.Name, stateEntity.PolishName); var settings = new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new DefaultTestPlatformContractResolver { NamingStrategy = new CamelCaseNamingStrategy() } }; return(JsonConvert.SerializeObject(stateResponse, settings)); }
private async Task SendCommandAsync(CommandConversation conversation, bool stopCheckingCoreState = false) { try { StateResponse response = await m_controller.Command( conversation, CreateTimeoutHandler(conversation.RequestData.Command), restartKeepaliveOnSuccess : !stopCheckingCoreState); HandleStateResponse(response); } catch (Exception ex) { HandleError(ex.Message); throw; } }
public async Task GetStateAsync_Should_Return_OkObjectResult_With_StateResponse() { var stateOutputQuery = new StateOutputQuery(Guid.NewGuid(), Array.Empty <byte>(), "Name", "PolishName"); var stateResponse = new StateResponse(stateOutputQuery.Id, stateOutputQuery.RowVersion, stateOutputQuery.Name, stateOutputQuery.PolishName); _getStateQueryHandlerMock .Setup(x => x.HandleAsync(It.IsAny <GetStateInputQuery>(), It.IsAny <CancellationToken>())) .ReturnsAsync(stateOutputQuery); _mapperMock.Setup(x => x.Map <StateOutputQuery, StateResponse>(It.IsAny <StateOutputQuery>())).Returns(stateResponse); var result = await _controller.GetStateAsync(stateOutputQuery.Id); var okResult = result.As <OkObjectResult>(); okResult.Value.Should().BeEquivalentTo(stateResponse); }
private static async Task <string> PrepareExpectedResponseAsync(RivaAdministrativeDivisionsDbContext context, string stateName) { var stateEntity = await context.States.SingleOrDefaultAsync(x => x.Name.Equals(stateName)); var stateResponse = new StateResponse(stateEntity.Id, stateEntity.RowVersion, stateEntity.Name, stateEntity.PolishName); var settings = new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = new DefaultTestPlatformContractResolver { NamingStrategy = new CamelCaseNamingStrategy() } }; return(JsonConvert.SerializeObject(stateResponse, settings)); }
public override void Invoke(MultiPartMessage msg) { string sessionId = ((Uri)msg.Metadata.Read("ReceiveUri")).Host; ClientSession session = SessionManager.Instance[sessionId]; msg.Data.Seek(0, SeekOrigin.Begin); StreamReader reader = new StreamReader(msg.Data, Encoding.Unicode); StateResponse stateResponse = (StateResponse)_serializer.Deserialize(reader); msg.Data.Seek(0, SeekOrigin.Begin); using (XmlReader xmlReader = XmlReader.Create(msg.Data)) { if (xmlReader.ReadToFollowing("StateResponse")) { string xml = xmlReader.ReadInnerXml(); byte[] hash = MD5.Create().ComputeHash(Encoding.Unicode.GetBytes(xml + DateTime.Now.Ticks.ToString())); //Added datetime to hash calculation to prevent loss of updates of identical layouts. StringBuilder sb = new StringBuilder(); for (int i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } stateResponse.HashCode = sb.ToString(); } } lock (session.SyncLock) { if (session.StateResponse != null && session.StateResponse.HashCode == stateResponse.HashCode) { return; } session.StateResponse = stateResponse; session.StateResponse.TraceLevel = session.ClientTraceLevel.ToString(); } session.StateChangedEvent.Set(); }
public StateResponse GetState(string playerid) { var sr = new StateResponse(); var pd = pdm.Load(playerid); if (pd != null) { if (qcm.GetQuest(pd.QuestIndex) is Quest q) { sr.TotalQuestPercentCompleted = GetTotalQuestPercentCompleted(pd.PointsEarned, q.PointsCompleted); sr.LastMilestoneIndexCompleted = pd.MilestoneIndex; sr.LastQuestIndexCompleted = pd.QuestIndex; } } return(sr); }
void myCurrencyManager_CurrentChanged(object sender, EventArgs e) { string id = Field("Id"); if (!string.IsNullOrEmpty(id)) { StateResponse state = currentConnection.GetSessionRender(Field("Id")); if (state != null && state.Form != null) { renderPanel.Visible = true; renderPanel.Render(state.Form); return; } } renderPanel.Visible = false; }
private async Task RepeatGetStateAsync(int repeatMillis, CancellationTokenSource tokenSource) { while (true) { if (IsCommandInProgress) { continue; } try { // TODO(): Handle timeout and other exceptions here. StateResponse stateCheckResult = await m_coreLink.Request(new GetStateConversation(), DefaultKeepaliveTimeoutMs) .ConfigureAwait(false); // Check this again - the cancellation could have come during the request. if (!tokenSource.IsCancellationRequested) { m_stateResultAction(new KeepaliveResult(stateCheckResult)); } } catch (Exception ex) { // TODO(HonzaS): if this keeps on failing, notify the user. Log.Warn("Periodic state check failed: {message}", ex.Message); m_stateResultAction(new KeepaliveResult(KeepaliveResultTag.RequestFailed)); } try { await Task.Delay(repeatMillis, tokenSource.Token).ConfigureAwait(false); } catch (Exception ex) { if (ex is TaskCanceledException) { return; } Log.Warn(ex, "Task.Delay threw an exception"); } } }
public async Task Consume(ConsumeContext <StatesRequest> context) { Console.Out.WriteLine($"Received: StatesRequest"); await Console.Out.WriteLineAsync("States response sent"); Configuration configuration = new Configuration(); using (StreamReader r = new StreamReader("configuration.json")) { string json = r.ReadToEnd(); configuration = JsonConvert.DeserializeObject <Configuration>(json); } var connectionString = "Server=localhost;Database=Locations;User ID=sa;Password=Ariel123!@;"; var DB_NAME = Environment.GetEnvironmentVariable("DB_NAME") ?? configuration.Database; var DB_HOST = Environment.GetEnvironmentVariable("DB_HOST") ?? configuration.DbHost; connectionString = connectionString.Replace(configuration.DbHost, DB_HOST); connectionString = connectionString.Replace(configuration.Database, DB_NAME); var optionsBuilder = new DbContextOptionsBuilder <LocationsDbContext>(); optionsBuilder.UseSqlServer(connectionString); var states = new LocationsDbContext(optionsBuilder.Options).States.ToList(); var statesResponse = new StateResponse(); foreach (var state in states) { statesResponse.States.Add(new Contracts.State { Id = state.Id, Name = state.Name }); } await context.RespondAsync(statesResponse); }
private void ParseNewState(StateResponse json) { foreach (string username in json.new_disconnections) { int index = GetButtonIndexByName(username); if (index != -1) { this.buttons[index].Text = ""; this.buttons[index].Enabled = false; } } foreach (string username in json.new_connections) { int index = EmptyButtonIndex(); if (index != -1) { this.buttons[index].Text = username; this.buttons[index].Enabled = true; } } if (json.requesting_user != "") { this.peer = json.requesting_user; this.label3.Text = this.peer + " Wants to control your screen"; this.acceptButton.Enabled = true; this.declineButton.Enabled = true; } if (json.target_answer != "") { if (json.target_answer == "accept") { this.ip = json.ip; this.port = json.port; IpLabel.Text = this.ip; PortLabel.Text = this.port.ToString(); ControllerForm cf = new ControllerForm(this.ip, this.port); cf.ShowDialog(); } } }
public async Task <ApiResponse <StateResponse> > GetStateByName(string nombre) { var result = new ApiResponse <StateResponse>(); var urlConfig = _config.Value; var urlApi = string.Concat(urlConfig.urlBase, urlConfig.methodName, nombre); var request = new HttpRequestMessage(HttpMethod.Get, urlApi); var client = _clientFactory.CreateClient(); var response = await client.SendAsync(request); if (response.IsSuccessStatusCode) { using var httpResponse = await response.Content.ReadAsStreamAsync(); var res = await JsonSerializer.DeserializeAsync <Country>(httpResponse); var state = res.provincias.FirstOrDefault(); if (state != null) { var resp = new StateResponse(latitud: state.centroide.lat, longitud: state.centroide.lon) { }; result.Data = resp; } else { result.Message = "Invalid state"; } result.Success = true; } else { result.Errors.Add(response.StatusCode.ToString()); } return(result); }
private static CoreState ReadState(StateResponse stateData) { switch (stateData.State) { case StateType.Empty: return(CoreState.Empty); case StateType.Running: return(CoreState.Running); case StateType.Paused: return(CoreState.Paused); case StateType.ShuttingDown: return(CoreState.ShuttingDown); case StateType.CommandInProgress: return(CoreState.CommandInProgress); default: throw new ArgumentOutOfRangeException(); } }
public void RenderState(StateResponse stateResponse) { bool centerToScreen = false; for (int i = 0; i < stateResponse.Beep; i++) { Console.Beep(); } if (stateResponse.Form != null) { renderPanel.Render(stateResponse.Form); SuspendLayout(); if (!_fullScreen) { if (Text == "IMI iWMS Thin Client") //First render size might change. Center screen { centerToScreen = true; } } Titlelabel.Text = stateResponse.Form.Text; Text = stateResponse.Form.Text; renderPanel.BorderStyle = BorderStyle.FixedSingle; ResumeLayout(); calibrateRenderPanel(); if (centerToScreen) { CenterToScreen(); } } }
public ListServersResponse ListServers(string host) { StateResponse stateResponse = RequestState(); var serversResponse = new ListServersResponse { Servers = stateResponse.Servers.Where(s => !s.IsPrivate).Select(s => new Server() { Port = s.Port, IsStarted = s.IsStarted, CommandLine = GetCommandLine(s, host), GameType = s.GameType, Mod = s.Mod.FriendlyName, CurrentPlayers = s.CurrentPlayers, MaximumPlayers = s.MaximumPlayers, Players = s.Players.Select(p => new Player() { Name = p.Name, Score = p.Score }).ToList(), SpawnedAtUtc = s.SpawnedAtUtc }).OrderBy(s => s.MaximumPlayers).ToList() }; return(serversResponse); }
private void HandleStateResponse(StateResponse response) { State = ReadState(response); }
public KeepaliveResult(StateResponse stateResponse) { StateResponse = stateResponse; }
public async Task <StateResponse> Command(CommandConversation conversation, Func <TimeoutAction> timeoutCallback, bool restartKeepaliveOnSuccess = true, int timeoutMs = CommandTimeoutMs) { if (m_runningCommand != null) { CommandType commandType = conversation.RequestData.Command; Log.Info("A command is already running: {commandType}", commandType); throw new InvalidOperationException($"A command is already running {commandType}"); } m_cancellationTokenSource.Cancel(); var retry = false; StateResponse result = null; while (true) { try { if (retry || m_runningCommand == null) { retry = false; m_runningCommand = m_coreLink.Request(conversation, timeoutMs); } result = await m_runningCommand.ConfigureAwait(false); } catch (TaskTimeoutException <StateResponse> ex) { TimeoutAction timeoutAction = timeoutCallback(); Log.Info("Command {command} timed out, {action} requested", conversation.RequestData.Command, timeoutAction); if (timeoutAction == TimeoutAction.Cancel) { break; } if (timeoutAction == TimeoutAction.Retry) { retry = true; } if (timeoutAction == TimeoutAction.Wait) { m_runningCommand = ex.OriginalTask.TimeoutAfter(CommandTimeoutMs); } continue; } catch (Exception ex) { Log.Error(ex, "Request failed"); m_runningCommand = null; RestartStateChecking(); throw; } Log.Debug("Successful command {command}", conversation.RequestData.Command); break; } m_runningCommand = null; if (restartKeepaliveOnSuccess) { RestartStateChecking(); } return(result); }