private async Task Producer(CancellationToken cancellationToken) { int producerCount = _cmdOptions.Count > 0 ? _cmdOptions.Count : 1; try { for (int i = 0; i < producerCount; i++) { if (cancellationToken.IsCancellationRequested) { break; } try { var messageData = new BusinessMessage { MessageId = i.ToString(),// "路由key",// i.ToString(), Content = $"我是内容_{i}", CreateTime = DateTime.Now }; await _messageBus.PublishAsync(messageData); _logger.LogInformation($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}生产数据:MessageId={messageData.MessageId}"); } catch (Exception ex) { _logger.LogError(ex, "生产消息出错"); } } } catch (Exception ex) { _logger.LogError(ex, ""); } }
public ActionResult DeleteElection(Guid id) { //removing an election means removing all votes and candidates of it try { _electionBusiness.DeleteElection(id); return(RedirectToAction(nameof(Index))); } catch (DataNotUpdatedException bnu) { //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View(nameof(Delete))); } catch (Exception E) { return(View()); } }
public IActionResult Index() { _logger.LogInformation("VoteController/Index() action is called"); try { //this action returns a view containing all candidates of the current election for the user to vote on five of them maximum _logger.LogInformation("Calling _voteBusiness.GetCandidatesViewModelList_OfCurrentElection() method"); List <CandidateViewModel> cvmList = _candidateBusiness.GetCandidatesViewModelList_OfCurrentElection(); _logger.LogInformation("Returning a list of CandidateViewModel to Index view"); return(View(cvmList)); } catch (BusinessException be) { _logger.LogError(be.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (Exception E) { _logger.LogError("Exception, " + E.Message); throw E; } }
private async Task <bool> Consumer2(BusinessMessage message) { var result = true; try { var current = Interlocked.Increment(ref Count); _logger.LogInformation($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}消费--2--数据:MessageId={message.MessageId},Content={message.Content},count={current}"); // await Task.Delay(10); //throw new System.ArgumentException("333"); // throw new BizException(1,"不重试"); //throw new Exception("重试异常"); await Task.CompletedTask; } catch (BizException ex) { result = true; } catch (Exception ex) { result = false; } return(result); }
public void Send(BusinessMessage businessMessage) { if (queueConnection == null) { lock (_lock) { if (queueConnection == null) { queueConnection = _connector.ConnectToQueue(_logger, _environment.BuildQueueSettings()); } } } try { _logger.LogDebug($"MessageSender:Send: '{businessMessage.CorrelationId}'"); using (var channel = queueConnection.CreateModel()) { channel.ExchangeDeclare(Constants.ArticlesExchange, ExchangeType.Fanout); string message = JsonConvert.SerializeObject(businessMessage); channel.BasicPublish(Constants.ArticlesExchange, Constants.RoutingKey, basicProperties: null, body: Encoding.UTF8.GetBytes(message)); _logger.LogDebug($"MessageSender:Send: '{businessMessage.CorrelationId}': SUCCESS"); } } catch (Exception ex) { _logger.LogError(ex.Message); throw; } }
public async Task <IActionResult> RemoveCandidate_byID([FromBody] string candidateId) { //this method is called using ajax calls //so if a business rule is not met we'll throw a businessException and catch it to create and internal server error and return its msg //as json //this function removes a candidate from the db using its ID .. used when editing an election try { _candidateBusiness.RemoveCandidateByID(candidateId); //row updated successfully in the DB return(Json(new { success = true })); } catch (DataNotUpdatedException bnu) { //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { //lets create an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that. HttpContext.Response.StatusCode = 500; return(Json(new { Message = be.Message })); } catch (Exception E) { //lets create and return an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that. HttpContext.Response.StatusCode = 500; return(Json(new { Message = E.Message })); } }
public IActionResult SendTestMessage() { try { var msg = new BusinessMessage() { Content = "some Content", CorrelationId = Guid.Parse(Constants.HelloWorldMessage) }; _logger.LogInformation($"SendTestMessage: created message {msg.CorrelationId}"); var id = _countersService.CreateRequest(new CountRequest() { Content = msg.Content, CorrelationId = msg.CorrelationId }); _logger.LogInformation($"SendTestMessage: stored in db {id}"); _messageSender.Send(msg); _logger.LogInformation($"SendTestMessage: sent {id}"); return(Content(msg.CorrelationId.ToString())); } catch (Exception ex) { _logger.LogError(ex.Message); return(StatusCode(500, ex.Message)); } }
public ActionResult Details(Guid id) { try { if (id == null) { throw new BusinessException(_messagesLoclizer["Passed parameter 'id' can not be null"]); } Election e = _electionBusiness.GetById(id); if (e == null) { throw new BusinessException(_messagesLoclizer["Election not found"]); } return(View(_electionBusiness.ConvertElection_ToElectionViewModel(e))); } catch (BusinessException be) { //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (Exception E) { throw E; } }
/// <summary> /// 获取业务数据 /// </summary> /// <param name="messgae"></param> /// <returns></returns> public BusinessResult ExecuteBusiness(string cmdkey, string args = "", BusinessType type = BusinessType.Get) { try { if (_BusinessServer == null) { return(null); } BusinessMessage msg = new BusinessMessage(); msg.BusinessCommand = cmdkey; msg.BusiType = type; msg.BusiPriority = BusinessPriority.Highest; msg.BusinessParam = args; BusinessResult bs = DeviceCommBusinessServerHelper.Instanse.ExecuteBusiness(msg); if (bs == null || !bs.Result) { return(null); } return(bs); } catch (Exception ex) { ErrorLog.Error(ex.StackTrace.ToString()); } return(null); }
public ActionResult <Result> Get(string jsonSearch) { ConcertBLL concert = new ConcertBLL(); IMessage message = BusinessMessage.CreateMessage(BusinessLocale.th_TH); Result result = concert.Get(jsonSearch, message); return(result); }
public ActionResult <Result> PostSearchConcert([FromBody] dynamic jsonSearch) { using (ConcertBLL concert = new ConcertBLL()) { IMessage message = BusinessMessage.CreateMessage(BusinessLocale.th_TH); Result result = concert.Get(jsonSearch.ToString(), message); return(result); } }
public ActionResult <Result> PostSearchConcert([FromBody] string jsonSearch) { // SetEnvironment(); ConcertBLL concert = new ConcertBLL(); IMessage message = BusinessMessage.CreateMessage(BusinessLocale.th_TH); Result result = concert.Get(jsonSearch, message); return(result); }
public IActionResult Edit(Guid Id) { _logger.LogInformation("Voter/Edit() action is called"); try { //In here we are going to return a view where a voter is displayed with his state but the state is in //a list of states if (Id == null) { _logger.LogError("Passed parameter 'id' is null"); throw new BusinessException(_messagesLoclizer["Passed parameter 'id' can not be null"]); } _logger.LogInformation("Calling VoterRepository.GetById() method"); var voter = _voterBusiness.GetById(Id); if (voter == null) { _logger.LogError("Voter not found"); throw new BusinessException(_messagesLoclizer["Voter not found"]); } _logger.LogInformation("Creating a VoterStateViewModel for the Voter instance"); VoterStateViewModel voterstate = new VoterStateViewModel { Id = voter.Id, FirstName = voter.FirstName, LastName = voter.LastName, States = _stateBusiness.GetAll() }; /*just in case user wanted to edit info of Neutral vote which doesn't have a state*/ if (voter.State != null) { voterstate.StateID = voter.State.Id; } _logger.LogInformation("Returning VoterStateViewModel to the View"); return(View(voterstate)); } catch (BusinessException be) { _logger.LogError(be.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (Exception E) { _logger.LogError("Exception, " + E.Message); throw E; } }
public IActionResult DeleteState(Guid id) { //we'll first update the Voters related to the State by making StateID in them 'null' then proceed removing the State row _logger.LogInformation("State/DeleteState() action is called"); try { if (id == null) { _logger.LogError("Passed parameter 'id' is null"); throw new BusinessException(_messagesLoclizer["Passed parameter 'id' can not be null"]); } _voterBusiness.MakeVotersStatesNull(id); _logger.LogInformation("Calling _stateBusiness.Delete() method"); int updatedRows2 = _stateBusiness.Delete(id); if (updatedRows2 > 0) { //row updated successfully in the DB _logger.LogInformation("Redirecting to Index view"); return(RedirectToAction(nameof(Index))); } else { //row not updated in the DB throw new DataNotUpdatedException(_messagesLoclizer["Data not updated, operation failed."]); } } catch (DataNotUpdatedException bnu) { _logger.LogError(bnu.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { _logger.LogError(be.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (Exception E) { _logger.LogError("Exception, " + E.Message); throw E; } }
public IActionResult Create(State state) { _logger.LogInformation("State/Create() action is called"); try { if (ModelState.IsValid) { _logger.LogInformation("Model is valid"); state.Id = Guid.NewGuid(); _logger.LogInformation("Calling _stateBusiness.Add() to add state instance to the DB"); int updatedRows = _stateBusiness.Add(state); if (updatedRows > 0) { //row updated successfully in the DB _logger.LogInformation("Stated added successfully, redirection to Index"); return(RedirectToAction(nameof(Index))); } else { //row not updated in the DB throw new DataNotUpdatedException(_messagesLoclizer["Data not updated, operation failed."]); } } //so the model isn't valid, lets keep the user in the same view so that he could read the validation msgs _logger.LogInformation("Model is not valid"); //so there is a business rule not met, lets throw a businessException and catch it throw new BusinessException(_messagesLoclizer["Information provided not valid"]); } catch (DataNotUpdatedException bnu) { _logger.LogError(bnu.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { _logger.LogError(be.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View(state)); } catch (Exception E) { //so something went wrong, lets log it and inform the user thru Error.cshtml to call the system admin _logger.LogError("Exception, " + E.Message); throw E; } }
public async Task <IActionResult> ValidateElection([FromBody] Election election) { //this method is called using ajax calls //so if a business rule is not met we'll throw a businessException and catch it to create and internal server error and return its msg //as json //Step(1): Adding info of the election(name, duration,,,) and send them to backend using api method in inside the controller, //then send back the response to javascript to redirect to step2 try { if (ModelState.IsValid) { election.Id = Guid.NewGuid(); _electionBusiness.AddNewElection(election); response_Voters_and_NewElection r; r.ElectionId = election.Id; r.Voters = _voterBusiness.ConvertVoterList_ToPersonViewModelList(_voterBusiness.GetAll()); //lets serialize the struct we've got and send it back as a reponse var json = JsonConvert.SerializeObject(r); return(Ok(json)); } else { //Model is not valid throw new BusinessException(_messagesLoclizer["Data not valid, please check again."]); } } catch (DataNotUpdatedException bnu) { //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { //lets create an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that. HttpContext.Response.StatusCode = 500; return(Json(new { Message = be.Message })); } catch (Exception E) { HttpContext.Response.StatusCode = 500; return(Json(new { Message = E.Message })); //In above code I created an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that. } }
public override OperationResult <CountResultRow> Process(BusinessMessage msg) { if (msg == null) { throw new ArgumentNullException(nameof(msg)); } var count = GetCount(msg.Content); return(OperationResult <CountResultRow> .Success(new CountResultRow() { CorrelationId = msg.CorrelationId, WordCount = count })); }
public IActionResult Edit(Guid id, State state) { _logger.LogInformation("State/Edit() action is called"); try { if (ModelState.IsValid) { _logger.LogInformation("Calling _stateBusiness.Edit() method"); int updatedRows = _stateBusiness.Edit(id, state); if (updatedRows > 0) { //row updated successfully in the DB _logger.LogInformation("Redirecting to Index view"); return(RedirectToAction(nameof(Index))); } else { //row not updated in the DB throw new DataNotUpdatedException(_messagesLoclizer["Data not updated, operation failed."]); } } //so there is a business rule not met, lets throw a businessException and catch it throw new BusinessException(_messagesLoclizer["Information provided not valid"]); } catch (DataNotUpdatedException bnu) { _logger.LogError(bnu.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { _logger.LogError(be.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View(state)); } catch (Exception E) { _logger.LogError("Exception, " + E.Message); throw E; } }
public async Task <IActionResult> DeleteVoter(Guid id) {//removing a voter means removing all his actions (votes & identity account) _logger.LogInformation("Voter/DeleteVoter() action is called"); try { if (id == null) { _logger.LogError("Passed parameter 'id' is null"); throw new BusinessException(_messagesLoclizer["Passed parameter 'id' can not be null"]); } _logger.LogInformation("Calling VoterRepository.GetById() method"); Voter voter = _voterBusiness.GetById(id); if (voter == null) { _logger.LogError("Voter not found"); throw new BusinessException(_messagesLoclizer["Voter not found"]); } await _voterBusiness.DeleteVoter(id); _logger.LogInformation("Redirecting to Index view"); return(RedirectToAction(nameof(Index))); } catch (DataNotUpdatedException bnu) { _logger.LogError(bnu.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { _logger.LogError(be.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View(nameof(Delete))); } catch (Exception E) { _logger.LogError("Exception, " + E.Message); throw E; } }
/// <summary> /// 增加一条记录 /// </summary> public long Insert(BusinessMessage businessMessage) { const string insertSql = @" insert into BusinessMessage(BusinessId,Content,IsRead) values(@BusinessId,@Content,@IsRead) select @@IDENTITY "; IDbParameters dbParameters = DbHelper.CreateDbParameters(); dbParameters.AddWithValue("BusinessId", businessMessage.BusinessId); dbParameters.AddWithValue("Content", businessMessage.Content); dbParameters.AddWithValue("IsRead", businessMessage.IsRead); object result = DbHelper.ExecuteScalar(SuperMan_Write, insertSql, dbParameters); //提现单号 return(ParseHelper.ToLong(result)); }
private async Task Producer(CancellationToken cancellationToken) { int producerCount = _cmdOptions.Count > 0 ? _cmdOptions.Count : 1; try { for (int i = 0; i < producerCount; i++) { if (cancellationToken.IsCancellationRequested) { break; } try { var messageData = new BusinessMessage { MessageId = i.ToString(), Content = $"我是内容_{i}", CreateTime = DateTime.Now }; await _messageBus.PublishAsync(messageData); //await _messageBus.PublishDelayAsync(messageData,TimeSpan.FromSeconds(8)); //await _messageBus.PublishCrontabAsync(messageData, new CrontabJobInfo //{ // JobId = "1", // JobName = "定时统计商品", // CrontabExpression = "0/1 * * * * *", // Status = CrontabJobStatus.Enabled //}); _logger.LogInformation($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")}生产数据:MessageId={messageData.MessageId}"); } catch (Exception ex) { _logger.LogError(ex, "生产消息出错"); } } } catch (Exception ex) { _logger.LogError(ex, ""); } }
public async Task <IActionResult> Create(VoterStateViewModel vs) { _logger.LogInformation("Voter/Create() action is called"); try { if (ModelState.IsValid) { _logger.LogInformation("Model is valid"); await _voterBusiness.AddNewVoter(vs); //row updated successfully in the DB _logger.LogInformation("The new voter is added to the DB successfully"); _logger.LogInformation("Redirecting to the Voter Index view"); return(RedirectToAction(nameof(Index))); } _logger.LogInformation("Model is not valid"); //so there is a business rule not met, lets throw a businessException and catch it throw new BusinessException(_messagesLoclizer["Information provided not valid"]); } catch (DataNotUpdatedException bnu) { _logger.LogError(bnu.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { _logger.LogError(be.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View(vs)); } catch (Exception E) { _logger.LogError("Exception, " + E.Message); throw E; } }
/// <summary> /// 执行业务命令 /// </summary> /// <param name="messgae"></param> /// <returns></returns> public BusinessResult ExecuteBusiness(BusinessMessage messgae, bool showBusy = false, string hint = "", string caption = "") { BusinessResult result = new BusinessResult() { Result = false }; try { if (_BusinessServer == null) { if (SOAClient.Instance.ServerCount < 4) { SOAClient.Instance.LoadServices(); } _BusinessServer = SOAClient.Instance.GetService <IBusinessLogicServer>(); if (showBusy) { MessageBox.Show(hint, caption, MessageBoxButtons.OK); } return(result); } BusinessResult businessResult = _BusinessServer.ExecuteBusiness(messgae); if (businessResult != null) { if (!businessResult.Result && showBusy) { if (result.ErrorCode != -1) { hint += ":" + result.ErrorCode.ToString(); } XtraMessageBox.Show(hint, caption, MessageBoxButtons.OK); } return(businessResult); } } catch (Exception ex) { ErrorLog.Error(ex.StackTrace.ToString()); } return(result); }
public IActionResult Details(Guid id) { _logger.LogInformation("State/Details() action is called"); try { if (id == null) { _logger.LogError("Passed parameter 'id' is null"); throw new BusinessException(_messagesLoclizer["Passed parameter 'id' can not be null"]); } _logger.LogInformation("Calling _stateBusiness.GetById() method"); State s = _stateBusiness.GetById(id); if (s == null) { _logger.LogError("State not found"); throw new BusinessException(_messagesLoclizer["State not found"]); } _logger.LogInformation("Calling _stateBusiness.ConvertState_ToStateViewModel() method"); StateViewModel svm = _stateBusiness.ConvertState_ToStateViewModel(s); _logger.LogInformation("Returning a StateViewModel to the Details view"); return(View(svm)); } catch (BusinessException be) { _logger.LogError(be.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (Exception E) { _logger.LogError("Exception, " + E.Message); throw E; } }
public async Task <IActionResult> EditElection([FromBody] TemporaryElection election) { //this method is called using ajax calls //so if a business rule is not met we'll throw a businessException and catch it to create and internal server error and return its msg //as json try { if (ModelState.IsValid) { _electionBusiness.EditElection(election); return(Json(new { success = true })); } else { //Model is not valid //so there is a business rule not met, lets throw a businessException and catch it throw new BusinessException(_messagesLoclizer["Data not valid, please check again."]); } } catch (DataNotUpdatedException bnu) { //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { //lets create an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that. HttpContext.Response.StatusCode = 500; return(Json(new { Message = be.Message })); } catch (Exception E) { HttpContext.Response.StatusCode = 500; return(Json(new { Message = E.Message })); //In above code I created an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that. } }
public IActionResult Post([FromBody] Dto dto) { try { if (dto == null) { throw new ArgumentNullException("dto"); } if (string.IsNullOrWhiteSpace(dto.Article)) { throw new ArgumentNullException("dto.Article"); } var msg = new BusinessMessage() { Content = dto.Article, CorrelationId = Guid.NewGuid() }; _logger.LogInformation($"Post: created message {msg.CorrelationId} content='{msg.Content}'"); var id = _countersService.CreateRequest(new CountRequest() { Content = msg.Content, CorrelationId = msg.CorrelationId }); _logger.LogInformation($"Post: stored in db {id}"); _messageSender.Send(msg); _logger.LogInformation($"Post: sent {id}"); return(Ok(msg.CorrelationId)); } catch (Exception ex) { _logger.LogError(ex.Message); return(StatusCode(500, ex.Message)); } }
public async Task <IActionResult> AddCandidate([FromBody] CandidateElectionRelation mydata) { //this method is called using ajax calls //it is used when editing/creating an election //it takes {voterId, electionId} and create new candidate from it and add it to db ... used when creating/editing an old election //so if a business rule is not met we'll throw a businessException and catch it to create and internal server error and return its msg //as json try { Candidate newCandidate = _candidateBusiness.AddNewCandidate(mydata.voterId, mydata.electionId); //row updated successfully in the DB //now lets return json data so that it is understandable by jQuery var json = JsonConvert.SerializeObject(new { candidateId = newCandidate.Id }); return(Ok(json)); } catch (DataNotUpdatedException bnu) { //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { //lets create an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that. HttpContext.Response.StatusCode = 500; return(Json(new { Message = be.Message })); } catch (Exception E) { //lets create and return an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that. HttpContext.Response.StatusCode = 500; return(Json(new { Message = E.Message })); } }
public IActionResult Delete(Guid id) { _logger.LogInformation("Voter/Delete() action is called"); try { if (id == null) { _logger.LogError("Passed parameter 'id' is null"); throw new BusinessException(_messagesLoclizer["Passed parameter 'id' can not be null"]); } _logger.LogInformation("Calling VoterRepository.GetById() method"); var voter = _voterBusiness.GetById(id); if (voter == null) { _logger.LogError("Voter not found"); throw new BusinessException(_messagesLoclizer["Voter not found"]); } _logger.LogInformation("Calling _voterBusiness.ConvertVoter_ToPersonViewModel() method"); PersonViewModel p = _voterBusiness.ConvertVoter_ToPersonViewModel(voter); _logger.LogInformation("Returning PersonViewModel to the view"); return(View(p)); } catch (BusinessException be) { _logger.LogError(be.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", be.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (Exception E) { _logger.LogError("Exception, " + E.Message); throw E; } }
private static void TestFacade() { LogUtil logger = new LogUtil(GetApplicationRoot() + "\\logs\\myapp.txt"); RestApiFacade facade = new RestApiFacade(logger); var aBook = new Book(); aBook.isbn = "434-5933-343"; aBook.title = "Java Script999"; aBook.price = 999; Puppy.Model.Message.IMessage message = BusinessMessage.CreateMessage(Puppy.Model.Business.BusinessLocale.th_TH); ExecuteModel model = new ExecuteModel { FileName = "D:\\Courses\\AspnetCore\\MyConcert\\MyConcert.BLL\\bin\\Debug\\netstandard2.0\\MyConcert.BLL.dll", ClassName = "MyConcert.BLL.ConcertBLL", MethodName = "Add", InitParameter = config, ExecuteParameter = aBook, Message = message, UaString = "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3" }; Result result = (Result)facade.ExecutionFlow(model); //InfoLog(result.Message); }
public async Task <IActionResult> ValidateVote([FromBody] List <string> candidateIdList) {//this action gets the list of the candidates ids that the user voted on, and add them to the db as vote objects, //and return a list of candidates ordered by number of votes //it can return two sort of Exception, one when voting, the second when retrieving results of the election _logger.LogInformation("VoteController/ValidateVote() method is called"); int exceptionDifferentiator = 0; try { int updatedRows = await _voteBusiness.AddVotes(candidateIdList); if (updatedRows != candidateIdList.Count()) { //not all rows updated in the DB throw new DataNotUpdatedException(_messagesLoclizer["Data not updated, operation failed."]); } _logger.LogInformation("Added Vote instance to the DB foreach Candidate"); exceptionDifferentiator = 1; //everything is okey, lets return a list of candidates with votes counter ordered so that the winner is the first _logger.LogInformation("Calling CandidateBusiness.GetCandidateViewModelList_byOneCandidateID() method"); List <CandidateViewModel> candidatesViewModel = _candidateBusiness.GetCandidateViewModelList_byOneCandidateID(Guid.Parse(candidateIdList.FirstOrDefault())); //lets serialize the list of candidatesviewmodel as json object _logger.LogInformation("Going to serialize the list of CandidateViewModels"); var json = JsonConvert.SerializeObject(candidatesViewModel.OrderByDescending(c => c.VotesCount)); _logger.LogInformation("Returning the list of CadidateViewModel as a json"); return(Ok(json)); } catch (DataNotUpdatedException bnu) { _logger.LogError(bnu.Message); //lets now create a suitable message for the user and store it inside a ViewBag (which is a Dynamic Object we can fill it //by whatever we want BusinessMessage bm = new BusinessMessage("Error", bnu.Message); ViewBag.BusinessMessage = bm; return(View()); } catch (BusinessException be) { _logger.LogError(be.Message); HttpContext.Response.StatusCode = 500; return(Json(new { Message = _messagesLoclizer["Error When Validating Votes!"] + " " + be.Message })); } catch (Exception E) { //there are two reasons for possible exceptions: one when voting, the second when retrieving results of the election if (exceptionDifferentiator == 0) { //so the exception happened when trying to validate the votes _logger.LogError("Exception When Validating Votes! " + E.Message); HttpContext.Response.StatusCode = 500; return(Json(new { Message = _messagesLoclizer["Error When Validating Votes!"] + " " + E.Message })); //In above code I created an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that. } else { //so the exception happened when trying to get the results of the election _logger.LogError("Exception When Trying to Get The Results! " + E.Message); HttpContext.Response.StatusCode = 500; return(Json(new { Message = _messagesLoclizer["Error When Trying to Get The Results!"] + " " + E.Message })); //In above code I created an internal server error so that the response returned is an ERROR, and jQuery ajax will understand that. } } }