예제 #1
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> SignIn(SignInModel model)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToDefault);
            }

            if (!ModelState.IsValid)
            {
                return(RedirectToDefault.WithError(JoinWithHtmlLineBreak(ModelState.GetErrorMessages())));
            }

            try
            {
                var signInResult = await _authService.SignInAsync(model.NameOrEmail, model.Password, false);

                if (signInResult.IsLockedOut)
                {
                    return(View("Lockout"));
                }

                return(signInResult.Succeeded
                    ? RedirectToDefault
                    : RedirectToDefault.WithError(MessagesOptions.LoginFailed));
            }
            catch (Exception exception)
            {
                _appLogger.LogError(exception);
                return(RedirectToDefault.WithError(exception.Message));
            }
        }
예제 #2
0
        //[ValidateAntiForgeryToken]
        public async Task <IActionResult> SetPassword(SetPasswordModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model).WithError(JoinWithHtmlLineBreak(ModelState.GetErrorMessages())));
            }

            try
            {
                var result = await _userService.SetPasswordAsync(model.UserId, model.Password);

                return(result.Succeeded
                    ? RedirectToDefault.WithSuccess("Password was set with success.")
                    : View(model).WithError(JoinWithHtmlLineBreak(result.GetAllErrors())));
            }
            catch (ValidationException validationException)
            {
                return(View(model).WithError(validationException.Message));
            }
            catch (Exception exception)
            {
                _appLogger.LogError(exception);
                return(View(model).WithError(MessagesOptions.GenericErrorMessage));
            }
        }
        public Task Initialize()
        {
            _logger.LogInfoMessage($"Serial port initializing on => portName:{_portName}, portSpeed:{_portSpeed}");
            _serialPort.SetPort(_portName, _portSpeed, StopBits.One, Parity.None, DataBits.Eight);
            var connectResult = _serialPort.Connect();

            if (!connectResult)
            {
                _logger.LogError($"Initializing: Serial port Connect - fail");
            }
            return(Task.CompletedTask);
        }
예제 #4
0
 public string GetConfigurationValue(ConfigurationType configurationType)
 {
     try
     {
         return(repository.GetConfigurationValue(configurationType));
     }
     catch (Exception e)
     {
         logger.LogError(e);
     }
     return(null);
 }
예제 #5
0
        public async Task <string> ComputeDescriptionAsync(double[] prediction)
        {
            try
            {
                var mostSimilarPhoto = await FindMostSimilarPhoto(prediction);

                return(mostSimilarPhoto?.Description);
            }
            catch (Exception exception)
            {
                _appLogger.LogError(exception);
                return("");
            }
        }
예제 #6
0
        private async void Desktop_Startup(object sender, ControlledApplicationLifetimeStartupEventArgs e)
        {
            var version = Assembly.GetEntryAssembly()?.GetName().Version;

            _logger.LogInfoMessage($"App startup begin. version:{version}");
            var settings = _settingsManager.GetAppSettings();

            _logger.LogInfoMessage($"App starting with user settings => :\n{JsonConvert.SerializeObject(settings, Formatting.Indented)}");

            _logger.LogInfoMessage("Connect to UGCS");
            await _ugcsConnection.ConnectAsync(settings.UGCSHost, settings.UGCSPort, settings.UGCSLogin, settings.UGCSPassword);

            if (_ugcsConnection.ConnectionStatus == UgcsConnectionStatus.Connected)
            {
                _logger.LogInfoMessage("Connected to UGCS");

                _logger.LogInfoMessage("Initialize VehicleManager");
                await _vehiclesManager.Initialize();

                _logger.LogInfoMessage("VehicleManager initialized");
            }
            else
            {
                _logger.LogError("Not connected to UGCS");
            }

            _logger.LogInfoMessage("Initialize PTZ transport");
            // TODO
            //await _ptzTransport.Initialize();
            _ptzTransport.Initialize();
            _logger.LogInfoMessage("PTZ transport initialized");

            _logger.LogInfoMessage("App startup end");
        }
예제 #7
0
 public bool Add(Ship ship, int shipOwnerId)
 {
     try
     {
         SetClosestSchedule(ship);
         var shipOwner = shipOwnerRepository.Find(shipOwnerId);
         ship.ShipOwner = shipOwner;
         repository.Add(ship);
         return(true);
     }
     catch (Exception e)
     {
         logger.LogError(e);
     }
     return(false);
 }
예제 #8
0
        public async Task <IActionResult> Get(int id)
        {
            try
            {
                var photo = await _photoService.GetAsync(id);

                if (photo == null)
                {
                    return(NotFound());
                }

                return(PhysicalFile(photo.Location, "image/jpg"));
            }
            catch (Exception exception)
            {
                _appLogger.LogError(exception);
                return(InternalServerErrorJsonResult(JsonResponse.ErrorResponse(exception)));
            }
        }
 public void CreateFooByUrl(string url)
 {
     try
     {
         // business logic
     }
     catch (Exception exception)
     {
         _logger.LogError(exception);
     }
 }
예제 #10
0
        public void Undo()
        {
            var memento = _caretaker.GetPreviousStateAndUpdateMemory();

            if (memento == null)
            {
                _logger.LogError("(Cart Client) The cart is empty");
                return;
            }
            _cart.Restore(memento);
            _logger.LogInfo("(Cart Client) Restored Cart to previous state");
        }
예제 #11
0
        public async Task AddAsync(T entity, string query)
        {
            using (var sqlConnection = OpenDbConnection())
            {
                try
                {
                    await sqlConnection.OpenAsync();

                    await sqlConnection.ExecuteAsync(query, entity);
                }
                catch (Exception exception)
                {
                    _applicationLogger.LogError(exception, exception.Message);
                    throw exception;
                }
                finally
                {
                    sqlConnection.Close();
                }
            }
        }
예제 #12
0
        public async Task <IActionResult> Get(string userName)
        {
            try
            {
                var user = await _userService.GetWithPhotoAsync(userName);

                var profilePhotoModel = Mapper.Map <PhotoModel>(Mapper.Map <PhotoDto>(user.ProfilePhoto));
                profilePhotoModel?.SetAddress(Url);
                var result = new
                {
                    FullName        = user.UserName,
                    UserName        = user.UserName,
                    ProfilePhoto    = profilePhotoModel,
                    CurrentUserName = _currentUserAccessor.UserName
                };

                return(ReadJsonResult(JsonResponse.SuccessResponse(result)));
            }
            catch (Exception exception)
            {
                _appLogger.LogError(exception);
                return(InternalServerErrorJsonResult(JsonResponse.ErrorResponse(exception)));
            }
        }
예제 #13
0
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            string controller = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string action     = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;

            if (actionExecutedContext.Response.IsSuccessStatusCode)
            {
                _logger.LogDebug($"Request, Method={actionExecutedContext.ActionContext.Request.Method.Method}, Url={actionExecutedContext.ActionContext.Request.RequestUri}, Controller={controller}, Action={action} successfull");
            }
            else
            {
                _logger.LogDebug($"Request, Method={actionExecutedContext.ActionContext.Request.Method.Method}, Url={actionExecutedContext.ActionContext.Request.RequestUri}, Controller={controller}, Action={action} failed");
                var exception = actionExecutedContext.Response.Content.ReadAsAsync <HttpError>().Result;
                _logger.LogError(exception);
                if (exception != null)
                {
                    StringBuilder error = new StringBuilder();
                    error.AppendLine(
                        $"Request, Method={actionExecutedContext.ActionContext.Request.Method.Method}, Url={actionExecutedContext.ActionContext.Request.RequestUri}, Controller={controller}, Action={action} failed");
                    error.AppendLine(CreateExceptionString(exception));
                    _logger.LogError(error.ToString());
                }
            }
        }
예제 #14
0
        private async Task <IActionResult> SearchAction <TRequest>(TRequest model,
                                                                   Func <TRequest, Task <IEnumerable <PhotoModel> > > innerSearchAction)
        {
            try
            {
                var photosModels = await innerSearchAction(model);

                photosModels.ForEach(x => x.SetAddress(Url));

                return(OkJsonResult(JsonResponse.SuccessResponse(photosModels)));
            }
            catch (Exception exception)
            {
                _appLogger.LogError(exception);
                return(InternalServerErrorJsonResult(JsonResponse.ErrorResponse(MessagesOptions.GenericErrorMessage)));
            }
        }
예제 #15
0
        private async Task <IActionResult> AdminAction(Func <Task <JsonResponse> > action)
        {
            var watch = Stopwatch.StartNew();

            try
            {
                var result = await action();

                return(OkJsonResult(result));
            }
            catch (Exception exception)
            {
                watch.Stop();
                _appLogger.LogError(exception);
                return(InternalServerErrorJsonResult(JsonResponse.ErrorResponse(new { exception, watch })));
            }
        }
예제 #16
0
 public bool Add(Schedule schedule, int shipId)
 {
     try
     {
         var ship = shipRepository.Find(shipId);
         ValidateSchedules(schedule, ship);
         UpdateClosestSchedule(schedule, ship);
         schedule.Ship = ship;
         repository.Add(schedule);
         return(true);
     }
     catch (Exception e)
     {
         logger.LogError(e);
     }
     return(false);
 }
예제 #17
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLogger logger)
        {
            try
            {
                app.UseSession();

                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/error");
                    app.UseStatusCodePagesWithReExecute("/error/{0}");
                }

                app.UseStaticFiles();
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider = new PhysicalFileProvider(Path.Combine(env.ContentRootPath, "clientapp")),
                    RequestPath  = new PathString("/clientapp")
                });

                app.UseAuthentication();
                app.UseMvc();

                if (bool.Parse(Configuration["imageProcessing:runOnStartup"]))
                {
                    RunImageProcessingAppAsync(logger).GetAwaiter().GetResult();
                }
            }
            catch (Exception exception)
            {
                logger.LogError(exception);
                throw;
            }
        }
예제 #18
0
        private async Task SendOldNotSentSchedules()
        {
            var now = DateTime.Now;

            now = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, 0, DateTimeKind.Local);
            foreach (var schedule in senderService.OldNotSentSchedules(now))
            {
                try
                {
                    if (!schedule.ArrivalSent && schedule.Arrival <= now)
                    {
                        await senderService.SendArrival(schedule);
                    }
                    if (!schedule.DepartureSent && schedule.Departure <= now)
                    {
                        await senderService.SendDeparture(schedule);
                    }
                }
                catch (Exception e)
                {
                    logger.LogError(e);
                }
            }
        }
예제 #19
0
        public void SendMessage(IPTZMessage message)
        {
            MessageSending?.Invoke(this, message.DataBytes);
            _logger.LogInfoMessage($"Post message. Data: {BitConverter.ToString(message.DataBytes)}");


            // for debug
            //if (message.DataBytes[3] == 0x51)
            //{
            //    Task.Factory.StartNew(async () =>
            //    {
            //        await Task.Delay(1000);
            //        byte[] sendBuffer = new byte[] { 0xff, 0x01, 0x00, 0x59, 0x08, 0x9c, 0xfe };
            //        MessageReceived?.Invoke(this, sendBuffer);
            //    });
            //}

            var postResult = _udpClient.Post(message.DataBytes);

            if (!postResult)
            {
                _logger.LogError($"Post message fail.");
            }
        }
예제 #20
0
 private static void logError(string message)
 {
     Terminal.WriteLine(message, ConsoleColor.Red);
     _logger.LogError(message);
 }