public async Task <StateDto> GetID(int ID) { StateDto stateDto = new StateDto(); State state = new State(); try { int CacheTimeOutInHours = this.configuration.GetValue <int>("MemoryCache:CacheTimeOutInHours"); if (CacheTimeOutInHours <= 0) { CacheTimeOutInHours = 1; } IEnumerable <State> states = new List <State>(); states = cache.Get <IEnumerable <State> >(string.Format("{0}", CacheEnum.STATES.ToString())); if (states == null || !states.Any()) { state = await this.stateRepository.GetByID(ID); return(this.mapper.Map <StateDto>(state)); } stateDto = this.mapper.Map <StateDto>(states.FirstOrDefault(x => x.StateID == ID)); } catch (Exception er) { logger.LogError(string.Format("{0}===================={1}====================\n", DateTime.Now.ToString(), er.ToString())); } return(stateDto); }
public async Task <Outcome <Sensor> > Update(int sensorId, StateDto stateDto) { var result = new Outcome <Sensor>(); if (!Enum.GetNames(typeof(SensorState)).Any(x => x.Equals(stateDto.State, StringComparison.InvariantCultureIgnoreCase))) { result.ErrorMessage = "State is not valid"; return(result); } var sensor = _uow.Repository <Sensor>().GetEntityWithSpec(new SensorSpecifications(a => a.SensorId == sensorId)).Result; if (sensor != null) { var auditData = _auditDataProvider.GetAuditList(DateTime.Now.Date, string.Empty, "Sensors", sensor.Farm.Name, sensor.SensorId); if (auditData != null && auditData.Any()) { sensor.RecordFlag = "Error"; } var state = Enum.GetNames(typeof(SensorState)).FirstOrDefault(x => x.Equals(stateDto.State, StringComparison.InvariantCultureIgnoreCase)); sensor.State = (SensorState)Enum.Parse(typeof(SensorState), state); sensor.UpdateDt = DateTime.Now; _uow.Repository <Sensor>().Update(sensor); int output = await _uow.Complete(); result.Result = sensor; } else { result.ErrorMessage = "Sensor not found"; } return(result); }
private static JobQueueDto CreateJobQueueDto(HangfireDbContext connection, string queue, bool isFetched) { var state = new StateDto(); AsyncHelper.RunSync(() => connection.State.InsertOneAsync(state)); var job = new JobDto { CreatedAt = connection.GetServerTimeUtc(), StateId = state.Id }; AsyncHelper.RunSync(() => connection.Job.InsertOneAsync(job)); var jobQueue = new JobQueueDto { Queue = queue, JobId = job.Id }; if (isFetched) { jobQueue.FetchedAt = connection.GetServerTimeUtc().AddDays(-1); } AsyncHelper.RunSync(() => connection.JobQueue.InsertOneAsync(jobQueue)); return(jobQueue); }
public override StateData GetStateData(string jobId) { if (jobId == null) { throw new ArgumentNullException("jobId"); } JobDto job = AsyncHelper.RunSync(() => _database.Job.Find(Builders <JobDto> .Filter.Eq(_ => _.Id, int.Parse(jobId))).FirstOrDefaultAsync()); if (job == null) { return(null); } StateDto state = AsyncHelper.RunSync(() => _database.State.Find(Builders <StateDto> .Filter.Eq(_ => _.Id, job.StateId)).FirstOrDefaultAsync()); if (state == null) { return(null); } return(new StateData { Name = state.Name, Reason = state.Reason, Data = JobHelper.FromJson <Dictionary <string, string> >(state.Data) }); }
public void ProcessingJobs_ReturnsProcessingJobsOnly_WhenMultipleJobsExistsInProcessingSucceededAndEnqueuedState() { CreateJobInState(_database, ObjectId.GenerateNewId(1), ProcessingState.StateName); CreateJobInState(_database, ObjectId.GenerateNewId(2), SucceededState.StateName, jobDto => { var processingState = new StateDto() { Name = ProcessingState.StateName, Reason = null, CreatedAt = DateTime.UtcNow, Data = new Dictionary <string, string> { ["ServerId"] = Guid.NewGuid().ToString(), ["StartedAt"] = JobHelper.SerializeDateTime(DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(500))) } }; var succeededState = jobDto.StateHistory[0]; jobDto.StateHistory = new[] { processingState, succeededState }; return(jobDto); }); CreateJobInState(_database, ObjectId.GenerateNewId(3), EnqueuedState.StateName); var resultList = _monitoringApi.ProcessingJobs(From, PerPage); Assert.Single(resultList); }
public void ProcessingJobs_ReturnsLatestStateHistory_WhenJobRequeued() { var oldServerId = "oldserverid"; var newServerId = "newserverid"; var oldStartTime = DateTime.UtcNow.AddMinutes(-30); var newStartTime = DateTime.UtcNow; CreateJobInState(_database, ObjectId.GenerateNewId(2), ProcessingState.StateName, jobDto => { var firstProcessingState = new StateDto() { Name = ProcessingState.StateName, Reason = null, CreatedAt = oldStartTime, Data = new Dictionary <string, string> { ["ServerId"] = oldServerId, ["StartedAt"] = JobHelper.SerializeDateTime(oldStartTime) } }; var latestProcessingState = jobDto.StateHistory[0]; latestProcessingState.CreatedAt = newStartTime; latestProcessingState.Data["ServerId"] = newServerId; latestProcessingState.Data["StartedAt"] = JobHelper.SerializeDateTime(newStartTime); jobDto.StateHistory = new[] { firstProcessingState, latestProcessingState }; return(jobDto); }); var resultList = _monitoringApi.ProcessingJobs(From, PerPage); Assert.Single(resultList); Assert.Equal(newServerId, resultList[0].Value.ServerId); Assert.Equal(newStartTime, resultList[0].Value.StartedAt); }
public void ProcessingJobs_MultipleJobsExistsInProcessingSucceededAndEnqueuedState_ReturnsProcessingJobsOnly() { // ARRANGE CreateJobInState(ProcessingState.StateName); CreateJobInState(SucceededState.StateName, visitor: jobDto => { var processingState = new StateDto() { Name = ProcessingState.StateName, Reason = null }; processingState.Data.Add(new StateDataDto("ServerId", Guid.NewGuid().ToString())); processingState.Data.Add(new StateDataDto("StartedAt", JobHelper.SerializeDateTime(DateTime.UtcNow.Subtract(TimeSpan.FromMilliseconds(500))))); jobDto.StateHistory.Insert(0, processingState); }); CreateJobInState(EnqueuedState.StateName); // ACT var resultList = _monitoringApi.ProcessingJobs(From, PerPage); Assert.AreEqual(1, resultList.Count); }
public void AddJobState(string jobId, IHangfireState state) { QueueCommand(() => { var job = Data.Get <JobDto>(jobId); if (job == null) { return; } DateTime createdAt = DateTime.UtcNow; Dictionary <string, string> serializedStateData = state.SerializeData(); var stateData = new StateDto { Id = AutoIncrementIdGenerator.GenerateId(typeof(StateDto)), JobId = jobId, Name = state.Name, Reason = state.Reason, CreatedAt = createdAt, Data = JobHelper.ToJson(serializedStateData) }; var stateHistory = new StateHistoryDto { StateName = state.Name, CreatedAt = createdAt, Reason = state.Reason, Data = serializedStateData }; job.History.Add(stateHistory); }); }
private bool InsertUpdateState(StateDto stateDto) { bool isSuccess = true; try { ObjectParameter paramStateCode = new ObjectParameter("stateCode", ""); int effectcount = _dbContext.uspStateInsert (stateDto.StateID, stateDto.State, stateDto.TEStateName, stateDto.IsActive, stateDto.UserID, DateTime.Now, paramStateCode); if (effectcount > 0) { isSuccess = true; } else { isSuccess = false; } } catch (Exception) { isSuccess = false; } return(isSuccess); }
public int AddStateRecord(StateDto state) { _context.States.Add(state); Console.WriteLine(state.Id); _context.SaveChanges(); return(state.Id); }
public StateDto InsertState(StateDto stateDto) { State state = _stateRepository.InsertState(_customAdapter.FromStateDtoToState(stateDto)); StateDto newStateDto = _stateRepository.GetState(state.StateId); return(newStateDto); }
/// <summary> /// Получение определенного состояния определенного пациента /// </summary> /// <param name="patientId"></param> /// <param name="stateId"></param> /// <returns>Состояние пациента</returns> public async Task <StateDto> GetStateAsync(int patientId, int stateId) { var state = await Db.StateEntities.FirstOrDefaultAsync(x => x.PatientId == patientId && x.StateId == stateId); var result = StateDto.FromEntity(state); return(result); }
public StateDto GetByID(int stateID) { StateDto stateDto = new StateDto(); List <uspStateGetByStateId_Result> lstuspStateGetByStateId_Result = _dbContext.uspStateGetByStateId(stateID).ToList(); stateDto = Mapper.Map <uspStateGetByStateId_Result, StateDto>(lstuspStateGetByStateId_Result.FirstOrDefault()); return(stateDto); }
public List <StateDto> GetAllState() { StateDto req = new StateDto(); req.SiteId = 1; var result = _masterRepository.GetAllState(req); return(result); }
public State FromStateDtoToState(StateDto stateDto) { return(new State { StateId = stateDto.StateId, Name = stateDto.Name, Abbreviation = stateDto.Abbreviation }); }
public async Task EditState(StateDto input) { var state = await _stateRepository.GetAsync(input.Id); state.Name = input.Name; state.Descreption = input.Descreption; state.CountryName = input.CountryName; await _stateRepository.UpdateAsync(state); }
public async Task <IActionResult> Put(int id, [FromBody] StateDto state) { if (ModelState.IsValid) { return(Ok(await this.stateService.UpdateState(id, state))); } return(BadRequest("Invalid Data")); }
public ActionResult Edit(StateDto state) { if (ModelState.IsValid) { var edit = AutoMapper.Mapper.Map <StateDto, State>(state); db.Entry(edit).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } return(View(state)); }
private void OnChangePoll(StateDto response) { targetState = response.state; if (!isLocked) { LoadTarget(); } StartPolling(); }
/// <summary> /// Создает пациента в базе данных /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <param name="birthDate"></param> /// <param name="sexType"></param> /// <returns>Новый пациент</returns> public async Task <PatientDto> CreatePatientAsync(string firstName, string lastName, DateTime birthDate, GenderType sexType) { var newPatient = new PatientEntity { FirstName = firstName, LastName = lastName, BirthDate = birthDate, GenderTypeId = sexType.Id }; Db.PatientEntities.Add(newPatient); await Db.SaveChangesAsync(); var newStatus = new StatusEntity { CreatedDate = DateTime.UtcNow, PatientId = newPatient.PatientId, PreviousStatusId = 0 }; Db.StatusEntities.Add(newStatus); await Db.SaveChangesAsync(); newStatus.PreviousStatusId = newStatus.StatusId; await Db.SaveChangesAsync(); var newState = new StateEntity { CreatedDate = DateTime.UtcNow, PatientId = newPatient.PatientId, StatusId = newStatus.StatusId, PreviousStateId = 0, StateTypeId = StateType.Initial.Id }; Db.StateEntities.Add(newState); await Db.SaveChangesAsync(); newState.PreviousStateId = newState.StatusId; await Db.SaveChangesAsync(); newPatient.StatusId = newStatus.StatusId; newPatient.StateId = newState.StateId; await Db.SaveChangesAsync(); var result = PatientDto.FromEntity(newPatient); result.Status = StatusDto.FromEntity(newStatus); result.PatientState = StateDto.FromEntity(newState); return(result); }
public StateDto Save(StateDto dto) { try { var retVal = this.dal.Save(dto.Id, dto.Name).ToDto(); return(retVal); } catch (Exception ex) { throw ex; } }
public async Task <ActionResult <SensorDto> > Update(int sensorId, [FromBody] StateDto stateDto) { var outcome = await _sensorDataProvider.Update(sensorId, stateDto); if (outcome.Successful) { var sensorDto = _mapper.Map <SensorDto>(outcome.Result); return(Ok(sensorDto)); } return(BadRequest(outcome.ErrorMessage)); }
public HttpResponseMessage updateState([FromBody] StateDto stateDto) { Order orderFromDb = db.Orders.Where(b => b.OrderId == stateDto.OrderId).First(); orderFromDb.State = stateDto.State; List <Order> bufferList = db.Orders.ToList(); //db.Orders.Add(orderFromDb); db.SaveChanges(); return(Request.CreateResponse(HttpStatusCode.OK, "State Updated")); }
public void GetStateData_ReturnsCorrectData() { UseConnection((database, connection) => { var data = new Dictionary <string, string> { { "Key", "Value" } }; var jobDto = new JobDto { Id = 1, InvocationData = "", Arguments = "", StateName = "", CreatedAt = database.GetServerTimeUtc() }; database.Job.Insert(jobDto); var jobId = jobDto.Id; database.State.Insert(new StateDto { Id = ObjectId.GenerateNewId(), JobId = jobId, Name = "old-state", CreatedAt = database.GetServerTimeUtc() }); var stateDto = new StateDto { Id = ObjectId.GenerateNewId(), JobId = jobId, Name = "Name", Reason = "Reason", Data = JobHelper.ToJson(data), CreatedAt = database.GetServerTimeUtc() }; database.State.Insert(stateDto); jobDto.StateId = stateDto.Id; database.Job.Save(jobDto); var result = connection.GetStateData(jobId.ToString()); Assert.NotNull(result); Assert.Equal("Name", result.Name); Assert.Equal("Reason", result.Reason); Assert.Equal("Value", result.Data["Key"]); }); }
public void SetJobState_AppendsAStateAndSetItToTheJob() { UseConnection(database => { JobDto job = new JobDto { Id = 1, InvocationData = "", Arguments = "", CreatedAt = database.GetServerTimeUtc() }; database.Job.InsertOne(job); JobDto anotherJob = new JobDto { Id = 2, InvocationData = "", Arguments = "", CreatedAt = database.GetServerTimeUtc() }; database.Job.InsertOne(anotherJob); var jobId = job.Id; var anotherJobId = anotherJob.Id; var state = new Mock <IState>(); state.Setup(x => x.Name).Returns("State"); state.Setup(x => x.Reason).Returns("Reason"); state.Setup(x => x.SerializeData()) .Returns(new Dictionary <string, string> { { "Name", "Value" } }); Commit(database, x => x.SetJobState(jobId.ToString(), state.Object)); var testJob = GetTestJob(database, jobId); Assert.Equal("State", testJob.StateName); Assert.NotNull(testJob.StateId); var anotherTestJob = GetTestJob(database, anotherJobId); Assert.Null(anotherTestJob.StateName); Assert.Equal(ObjectId.Empty, anotherTestJob.StateId); StateDto jobState = database.State.Find(new BsonDocument()).ToList().Single(); Assert.Equal(jobId, jobState.JobId); Assert.Equal("State", jobState.Name); Assert.Equal("Reason", jobState.Reason); Assert.NotNull(jobState.CreatedAt); Assert.Equal("{\"Name\":\"Value\"}", jobState.Data); }); }
public List <StateDto> GetAllState(StateDto req) { List <StateDto> lstState = new List <StateDto>(); try { var state = MasterContext.State.Where(i => i.SiteId == req.SiteId).ToList(); lstState = Mapper.Convert <StateDto, State>(state); } catch (Exception ex) { } return(lstState); }
public override void AddJobState(string jobId, IState state) { var filter = CreateJobIdFilter(jobId); var stateDto = new StateDto { Name = state.Name, Reason = state.Reason, CreatedAt = DateTime.UtcNow, Data = state.SerializeData() }.ToBsonDocument(); var update = new BsonDocument("$push", new BsonDocument(nameof(JobDto.StateHistory), stateDto)); JobGraph.UpdateOne(SessionHandle, filter, update); }
public async Task <IActionResult> AddSubscription(StateDto stateDto) { try { var state = _mapper.Map <State>(stateDto); _stateService.AddState(state); await _unitOfWork.Save(); return(Ok(state)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public static StateDto ToDto(this DataAccess.Models.State item) { StateDto dto = null; if (item != null) { dto = new StateDto { Id = item.Id, Name = item.Name }; } return(dto); }
public StateDto Add(StateDto entity) { entity.Id = Guid.NewGuid(); _repository.Add(new State { Id = entity.Id, Title = entity.Title, FlowId = entity.FlowId, PreviousStateId = entity.PreviousStateId, NextStateId = entity.NextStateId }); UpdateRelationalStatesWithNewState(entity); return(entity); }
/// <summary> /// The read states. /// </summary> /// <param name="process">The process.</param> /// <param name="sr">The reader.</param> private static void ReadStates(ProcessEditDto process, SafeDataReader sr) { sr.NextResult(); while (sr.Read()) { var stateDto = new StateDto { Id = sr.GetInt32(0), Name = sr.GetString(1), Documentation = sr.GetString(2), DesignPositionLeft = sr.GetDouble(3), DesignPositionTop = sr.GetDouble(4), DesignDecisionPositionLeft = sr.GetDouble(5), DesignDecisionPositionTop = sr.GetDouble(6), Guid = sr.GetGuid(7), MetaId = sr.GetInt32(8), Color = sr.GetInt64("Color") }; process.States.Add(stateDto); } ReadConnectors(process, sr); }
/// <summary> /// Updates state. /// </summary> /// <param name="dto">The DTO object.</param> /// <param name="locDto">The localization DTO object.</param> /// <exception cref="System.ArgumentNullException"></exception> /// <exception cref="System.Data.DBConcurrencyException">Indicates stale data.</exception> /// <exception cref="System.ArgumentException">The input DTO is null.</exception> public void UpdateStateWithLocalization(StateDto dto, StateLocalizationDto locDto) { if (dto == null) throw new ArgumentNullException(string.Format(CultureInfo.InvariantCulture, Resources.NullArguementException, "dto")); const string CmdText = @" UPDATE [dbo].[States] SET [ProcessId] = @ProcessId, [Color] = @Color, [DesignPositionLeft] = @DesignPositionLeft, [DesignPositionTop] = @DesignPositionTop, [DesignDecisionPositionLeft] = @DesignDecisionPositionLeft, [DesignDecisionPositionTop] = @DesignDecisionPositionTop, [Guid] = @Guid, [LastModifiedOn] = getdate() WHERE [Id] = @Id"; using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.VeyronMeta, false)) { var cn = ctx.Connection; using (var cmd = new SqlCommand(CmdText, cn)) { cmd.Parameters.AddWithValue("@Id", dto.Id); cmd.Parameters.AddWithValue("@ProcessId", dto.ProcessId); cmd.Parameters.AddWithValue("@Color", dto.Color); cmd.Parameters.AddWithValue("@DesignPositionLeft", dto.DesignPositionLeft); cmd.Parameters.AddWithValue("@DesignPositionTop", dto.DesignPositionTop); cmd.Parameters.AddWithValue("@DesignDecisionPositionLeft", dto.DesignDecisionPositionLeft); cmd.Parameters.AddWithValue("@DesignDecisionPositionTop", dto.DesignDecisionPositionTop); cmd.Parameters.AddWithValue("@Guid", dto.Guid); var rowsAffetcted = cmd.ExecuteNonQuery(); if (rowsAffetcted == 0) { throw new DBConcurrencyException(Resources.StaleDataException); } } } UpdateStateLocalization(locDto); }
/// <summary> /// Inserts state. /// </summary> /// <param name="dto">The DTO object.</param> /// <exception cref="System.ArgumentNullException">The input DTO is null.</exception> public void InsertState(StateDto dto) { if (dto == null) throw new ArgumentNullException(string.Format(CultureInfo.InvariantCulture, Resources.NullArguementException, "dto")); const string CmdText = @" INSERT INTO [dbo].[States] ( [ProcessId], [Name], [Documentation], [Color], [DesignPositionLeft], [DesignPositionTop], [DesignDecisionPositionLeft], [DesignDecisionPositionTop], [Guid], [LastModifiedOn] ) VALUES ( @ProcessId, @Name, @Documentation, @Color, @DesignPositionLeft, @DesignPositionTop, @DesignDecisionPositionLeft, @DesignDecisionPositionTop, @Guid, getdate() ); SELECT [Id] FROM [dbo].[States] WHERE [Id] = SCOPE_IDENTITY()"; using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.VeyronMeta, false)) { var cn = ctx.Connection; using (var cmd = new SqlCommand(CmdText, cn)) { cmd.Parameters.AddWithValue("@ProcessId", dto.ProcessId); cmd.Parameters.AddWithValue("@Name", dto.Name); cmd.Parameters.AddWithValue("@Documentation", dto.Documentation); cmd.Parameters.AddWithValue("@Color", dto.Color); cmd.Parameters.AddWithValue("@DesignPositionLeft", dto.DesignPositionLeft); cmd.Parameters.AddWithValue("@DesignPositionTop", dto.DesignPositionTop); cmd.Parameters.AddWithValue("@DesignDecisionPositionLeft", dto.DesignDecisionPositionLeft); cmd.Parameters.AddWithValue("@DesignDecisionPositionTop", dto.DesignDecisionPositionTop); cmd.Parameters.AddWithValue("@Guid", dto.Guid); dto.Id = (int)cmd.ExecuteScalar(); } } }