Ejemplo n.º 1
0
        public List <LSet> BuilderAssistent(int userId)
        {
            var user = userRepository.GetById(userId);

            if (user != null)
            {
                var avaliableParts = user.LSets.Where(s => (s.Owned > s.Built)).SelectMany(x => x.LSet.LSetParts).ToList();
                foreach (var part in avaliableParts)
                {
                    var set = user.LSets.FirstOrDefault(s => s.LSet.Id == part.LSet.Id);
                    part.Number = (set.Owned - set.Built) * part.Number;
                }

                var possibleSets = lSetRepository.Query().Where(s => s.LSetParts.Count() > 0).ToList().Where(
                    s => s.LSetParts.All(
                        part => avaliableParts.Any(b => b.Color.Id == part.Color.Id) &&
                        avaliableParts.Any(b => b.Part.Id == part.Part.Id) &&
                        avaliableParts.Any(b => b.Number >= part.Number)))
                                   .ToList();

                return(possibleSets);
            }
            else
            {
                throw new UserException(UserException.UserExceptionsText(UserExceptionEnum.NotFound));
            }
        }
Ejemplo n.º 2
0
        public ValidationInformation RegistrationValidation(UIOrganization uIOrganization)
        {
            Repository <Organization> repository = new Repository <Organization>();

            if (uIOrganization.Name.Length < 6)
            {
                UserException.LogInformation("OrganizationName length should be 6 or More");
                this.validation.ErrorMessages.Add("OrganizationName length should be 6 or More");
            }
            else
            {
                var IsOrganization = repository.Find(t => t.IsActive && t.Name == uIOrganization.Name);
                if (IsOrganization != null && !string.IsNullOrEmpty(IsOrganization.Name))
                {
                    UserException.LogInformation("OrganizationName name is already present" + uIOrganization.Name);
                    this.validation.ErrorMessages.Add("OrganizationName is already present, Can you try some other name");
                }
                else
                {
                    IsOrganization = repository.Find(t => t.IsActive && t.Email == uIOrganization.Email);
                    if (IsOrganization != null && !string.IsNullOrEmpty(IsOrganization.Email))
                    {
                        UserException.LogInformation("OrganizationEmail is already present" + uIOrganization.Name);
                        this.validation.ErrorMessages.Add("OrganizationEmail is already present, Can you try some other E-Mail");
                    }
                }
            }

            if (this.validation.ErrorMessages.Count == 0)
            {
                this.validation.IsSuccess = true;
            }

            return(this.validation);
        }
Ejemplo n.º 3
0
        public override void OnException(ExceptionContext context)
        {
            if (context.Exception is UserException)
            {
                UserException izuzetak = context.Exception as UserException;
                foreach ((string key, string msg)x in izuzetak.Errori)
                {
                    context.ModelState.AddModelError(x.key, x.msg);
                }
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
            }
            else if (context.Exception is AuthorizeException)
            {
                AuthorizeException izuzetak = context.Exception as AuthorizeException;
                context.ModelState.AddModelError("", izuzetak.Message);
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
            }
            else
            {
                context.ModelState.AddModelError("ERROR", "Greska na serveru");
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
            var lista = context.ModelState.Where(x => x.Value.Errors.Count() > 0)
                        .ToDictionary(x => x.Key, y => y.Value.Errors.Select(c => c.ErrorMessage));

            context.Result = new JsonResult(lista);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Looks for a new message to process
        /// </summary>
        public void Handle()
        {
            try
            {
                try
                {
                    TryProcessIncomingMessage();
                }
                catch (MessageException exception)
                {
                    UserException?.Invoke(this, new MessageErrorEventArgs(exception));
                }
                catch (CommitException exception)
                {
                    UserException?.Invoke(this, new MessageErrorEventArgs(exception));
                }
                catch (Exception e)
                {
                    SystemException?.Invoke(this, new MessageErrorEventArgs(e));

                    //generic exceptions tend to indicate a serious problem - lets start delaying processing
                    //this counter will reset once a message has been processed by this thread
                    _seriousExceptionProcessBackOffHelper.Value.Wait();
                }
            }
            catch (Exception ex) //not cool - one of the exception events threw an exception
            {
                //there isn't a whole lot we can do here
                _log.ErrorException("An error has occurred while trying to handle an exception", ex, null);
            }
        }
Ejemplo n.º 5
0
        public Moc RemoveMoc(int userId, int mocId)
        {
            var user = userRepository.GetById(userId);
            if (user != null)
            {
                var dbMOC = mocRepository.GetById(mocId);
                if (dbMOC != null)
                {
                    if(dbMOC.User.Id != userId)
                    {
                        throw new DataException("MOC is not yours!");
                    }
                    else
                    {
                        var query = mocPartRepository.Query().Where(x => x.Moc.Id == dbMOC.Id).ToList();
                        foreach (var q in query)
                        {
                            mocPartRepository.Delete(q);
                        }
                        mocRepository.Delete(dbMOC);
                        return dbMOC;
                    }
                }
                else
                {
                    throw new DataException("MOC not found!");
                }
            }

            throw new UserException(UserException.UserExceptionsText(UserExceptionEnum.NotFound));
        }
Ejemplo n.º 6
0
        private void ValidirajUpdateSliku(int id, Fajl Slika)
        {
            UserException exception = new UserException();

            Igrac igrac = db.Igraci.Find(id);

            if (igrac == null)
            {
                exception.AddError(nameof(Igrac), "Igrac ne smije biti null.");
            }

            if (Slika == null)
            {
                exception.AddError(nameof(Slika), "Morate uploadat sliku.");
            }

            if (!IsDozvoljenTip(Slika))
            {
                exception.AddError(nameof(Slika), "Nedozovljen format fajla. Mozete uploadati samo slike.");
            }

            if (exception.Errori.Count > 0)
            {
                throw exception;
            }
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> Edit(int id, [Bind("id,project_name,error_text,dateTime")] UserException userException)
        {
            if (id != userException.id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(userException);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!UserExceptionExists(userException.id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(userException));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Handles the exception.
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <param name="policyName">Name of the policy.</param>
        /// <returns></returns>
        public bool HandleException(ref System.Exception exception, string policyName)
        {
            try
            {
                if (exception is UserException)
                {
                    return(true);  // Propagate Policy
                }
                else
                {
                    // logs the exception
                    FWUtils.ExpLogUtils.ExceptionLogger.LogError(exception, null);

                    // tries to translate an exception before showing it to the user
                    ExceptionTranslator t = new ExceptionTranslator();
                    exception = t.TryToTranslate(exception); // if translation is successful, it created a UserException
                }
            }
            catch (Exception)
            {
                // Excution should never be here
                exception = new UserException(StringMsgs.Exceptions.UnknownExceptionHappened);
                return(false);
            }

            return(true);
        }
Ejemplo n.º 9
0
        public async Task <LoggedInUserDto> LoginAsync(Credentials credentials)
        {
            var loggedUserData = await this.modelContext.Users
                                 .Where(u => u.Credentials.Mail == credentials.Mail)
                                 .AsNoTracking()
                                 .Select(u => new
            {
                u.Credentials,
                u.Id,
                u.Role,
                IsConfirmed = u.IsSubscriptionValid(this.dtoService)
            }).FirstOrDefaultAsync();

            if (loggedUserData == null)
            {
                throw UserException.WrongMailException(credentials.Mail);
            }

            if (loggedUserData.Credentials != credentials)
            {
                throw UserException.WrongPasswordException(credentials.Mail);
            }

            if (loggedUserData.Role == User.UserRole.Registered && !loggedUserData.IsConfirmed)
            {
                throw UserException.UserNotConfirmedException(loggedUserData.Id);
            }

            return(new LoggedInUserDto()
            {
                Id = loggedUserData.Id,
                Role = loggedUserData.Role
            });
        }
Ejemplo n.º 10
0
        UnitTestResult ReportLoadError(TestContext testContext)
        {
            var exception = new UserException(
                GettextCatalog.GetString("Unable to run tests. Test discovery failed."));

            return(ReportRunFailure(testContext, exception));
        }
Ejemplo n.º 11
0
        private UserException TryAuthenticate(string accessToken, out ClaimsIdentity identity)
        {
            JwtTokenPayload payload;

            identity = null;
            try
            {
                payload = _jwtDecoder.DecodeToObject <JwtTokenPayload>(accessToken, _options.JwtSecret, false);
            }
            catch (Exception ex)
            {
                _logger.Warning(ex, $"Failed to parse authentication token: {ex.Message}");
                return(UserException.Create(AuthenticationError.BadToken, "Invalid authentication token."));
            }
            if (payload.ExpiresAt < DateTime.UtcNow)
            {
                return(UserException.Create(AuthenticationError.ExpiredToken, "Authentication token is expired."));
            }
            var parsed = Guid.TryParse(payload.Subject, out Guid userId);

            if (!parsed)
            {
                return(UserException.Create(AuthenticationError.BadToken, "Invalid subject."));
            }
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, userId.ToString())
            };

            identity = new ClaimsIdentity(claims);
            return(null);
        }
Ejemplo n.º 12
0
        public static void SendMail(string body, string subject, string to, string userName, string pwd = null)
        {
            try
            {
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient("ciibe-onlineassessment.in");

                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add(to);
                mail.Subject = subject;

                string emailbody = body.Replace("<<Name>>", userName);
                emailbody = emailbody.Replace("<<userid>>", to);
                if (pwd != null)
                {
                    emailbody = emailbody.Replace("<<pwd>>", pwd);
                }

                mail.Body              = emailbody;
                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "mynameisKANTH@2019");
                SmtpServer.Send(mail);
            }
            catch (Exception ex)
            {
                UserException.LogException(ex);
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Handle user-facing error
 /// </summary>
 ///
 static void HandleUserException(UserException ue)
 {
     EventHandlerPipeline.Raise(new ProgramUserErrorEvent()
     {
         Message = ue.Message
     });
 }
Ejemplo n.º 14
0
        public async Task <SharedModels.Users> ConfirmPasswordChange(string loggedInUserName, PasswordPromjena obj)
        {
            var user = await usermanager.FindByEmailAsync(loggedInUserName);

            if (user != null)
            {
                if (obj.password != obj.potvrdaPassword)
                {
                    throw new UserException("Passwordi se ne slazu.");
                }

                var rezultat = await usermanager.ResetPasswordAsync(user, obj.token, obj.password);

                if (rezultat.Succeeded)
                {
                    var i = db.Igraci.Find(user.Id);
                    return(mapper.Map <SharedModels.Users>(i));
                }
                else
                {
                    UserException exception = new UserException();

                    foreach (var error in rezultat.Errors)
                    {
                        exception.AddError("", error.Description);
                    }

                    throw exception;
                }
            }
            throw new UserException("User ne postoji u bazi.");
        }
Ejemplo n.º 15
0
        public async Task <Users> Login(Login obj)
        {
            var korisnik = await usermanager.FindByEmailAsync(obj.UserName);

            if (korisnik == null)
            {
                UserException ex = new UserException();
                ex.AddError("", "Neispravni podaci za login");
                throw ex;
            }

            var igrac = db.Igraci.Find(korisnik.Id);

            var rezultat = await signinmanager.CheckPasswordSignInAsync(korisnik, obj.Password, false);

            if (rezultat.IsLockedOut)
            {
                TimeSpan t = (korisnik.LockoutEnd - DateTime.Now) ?? default(TimeSpan);
                throw new Exception("Vaš profil je zaključan još " + t.Minutes + " minuta i " + t.Seconds + " sekundi.");
            }
            else if (rezultat.Succeeded)
            {
                var povratni = Get(igrac.ID);
                return(povratni);
            }
            else if (await signinmanager.UserManager.CheckPasswordAsync(korisnik, obj.Password))
            {
                throw new UserException("Morate potvrditi mejl prije logiranja");
            }
            else
            {
                throw new UserException("Korisnik ne postoji");
            }
        }
Ejemplo n.º 16
0
        static void Run()
        {
            Test();
            var ex = new UserException("This exception was forced by dev: "); //created exception

            ex.NumberInError = 42;
            throw ex;
        }
Ejemplo n.º 17
0
        public void UserExceptionConstructorTest()
        {
            return;

            UserException target = new UserException("Foo");

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Ejemplo n.º 18
0
        static void Run()
        {
            Test();
            var ex = new UserException("This exception was forced!");

            ex.NumberInError = 88;
            throw ex;
        }
Ejemplo n.º 19
0
 private static string GetErrorMessage(UserException exception, IErrorHandler errorHandler)
 {
     if (exception is ValidationErrorsException)
     {
         return(GetErrorMessage(((ValidationErrorsException)exception).Errors, errorHandler));
     }
     return(errorHandler.FormatErrorMessage(exception));
 }
Ejemplo n.º 20
0
        private string ValidateName(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw UserException.InvalidNameException(name);
            }

            return(name);
        }
Ejemplo n.º 21
0
        private byte[] ValidateProfilePhoto(byte[] profilePhoto)
        {
            if ((profilePhoto?.Length ?? 0) == 0)
            {
                throw UserException.InvalidProfilePhotoException(profilePhoto);
            }

            return(profilePhoto);
        }
Ejemplo n.º 22
0
        private void EnsureTurnIsInProgress(Guid userId)
        {
            var state = _state.PlayerStates.GetOrCreateDefault(userId);

            if (state.TurnStatus == TurnStatus.Ended)
            {
                throw UserException.Create(GameplayError.TurnIsAlreadyEnded, "You have already ended your turn.");
            }
        }
Ejemplo n.º 23
0
        private string ValidateLastName(string lastName)
        {
            if (string.IsNullOrEmpty(lastName))
            {
                throw UserException.InvalidLastNameException(lastName);
            }

            return(lastName);
        }
Ejemplo n.º 24
0
        private void EnsureGameIsNotStarted()
        {
            if (!_state.IsGameStarted)
            {
                return;
            }
            var message = $"Game {_state.RoomId} is already in progress.";

            throw UserException.Create(GameplayError.GameIsAlreadyInProgress, message);
        }
        /// <summary>
        /// Create.
        /// </summary>
        /// <param name="userException">The user exception containing the dispayed message.</param>
        public UserErrorModel(UserException userException)
        {
            if (userException == null)
            {
                throw new ArgumentNullException(nameof(userException));
            }

            this.DisplayMessage = userException.Message;
            this.ExceptionName  = userException.GetType().FullName;
        }
Ejemplo n.º 26
0
        public T GetOrThrow <T>(Guid id) where T : MasterDataObject
        {
            var item = Get <T>(id);

            if (item == null)
            {
                throw UserException.Unknown <T>(() => id);
            }
            return(item);
        }
Ejemplo n.º 27
0
        public User Login(string email, string password)
        {
            var user = userRepository.Query().FirstOrDefault(u => u.Email == email && u.Password == password);

            if (user != null)
            {
                return(user);
            }
            throw new UserException(UserException.UserExceptionsText(UserExceptionEnum.NotFound));
        }
Ejemplo n.º 28
0
        public UserApi Login(LoginModel data)
        {
            if (string.IsNullOrEmpty(data.Email) || string.IsNullOrEmpty(data.Password))
            {
                throw new UserException(UserException.UserExceptionsText(UserExceptionEnum.InvalidData));
            }

            var user = Mapper.Map <UserApi>(korisnikServices.Login(data.Email, data.Password));

            return(user);
        }
Ejemplo n.º 29
0
        public UserApi Register(UserApi newUser)
        {
            if (!ModelState.IsValid)
            {
                throw new UserException(UserException.UserExceptionsText(UserExceptionEnum.InvalidData));
            }

            var newUserSaved = Mapper.Map <UserApi>(korisnikServices.Register(Mapper.Map <User>(newUser)));

            return(newUserSaved);
        }
Ejemplo n.º 30
0
        public async Task <IActionResult> Create([Bind("id,project_name,error_text,dateTime")] UserException userException)
        {
            if (ModelState.IsValid)
            {
                _context.Add(userException);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(userException));
        }
Ejemplo n.º 31
0
        async Task<RecoveryOptionResult> BasicMessageHandler(UserError userError, Window window) {
            MainLog.Logger.Error(userError.InnerException.Format());
            var id = Guid.Empty;
#if !DEBUG
            var ex = new UserException(userError.ErrorMessage, userError.InnerException);
            id = ex.Id;
            Report(ex);
#endif
            // NOTE: this code really shouldn't throw away the MessageBoxResult
            var message = userError.ErrorCauseOrResolution +
                          "\n\nWe've been notified about the problem (Your ID: " + id + ")." +
                          "\n\nPlease make sure you are running the latest version of the software.\n\nIf the problem persists, please contact Support: http://community.withsix.com";
            var title = (userError.ErrorMessage ?? "An error has occured while trying to process the action");
            var result =
                await
                    _dialogManager.MessageBoxAsync(new MessageBoxDialogParams(message, title) {Owner = window})
                        .ConfigureAwait(false);
            return RecoveryOptionResult.CancelOperation;
        }
Ejemplo n.º 32
0
        /// <summary>
        /// See ISqlUtility.InterpretSqlException.
        /// </summary>
        public RhetosException InterpretSqlException(Exception exception)
        {
            if (exception == null || exception is RhetosException)
                return null;

            var sqlException = (SqlException)ExtractSqlException(exception);
            if (sqlException == null)
                return null;

            //=========================
            // Detect user message in SQL error:

            const int userErrorCode = 101; // Rhetos convention for an error raised in SQL that is intended as a message to the end user.

            if (sqlException.State == userErrorCode)
                return new UserException(sqlException.Message, exception);

            if (sqlException.Errors != null)
            foreach (var sqlError in sqlException.Errors.Cast<SqlError>().OrderBy(e => e.LineNumber))
                if (sqlError.State == userErrorCode)
                    return new UserException(sqlError.Message, exception);

            //=========================
            // Detect system errors:

            if (sqlException.Number == 229 || sqlException.Number == 230)
                if (sqlException.Message.Contains("permission was denied"))
                    return new FrameworkException("Rhetos server lacks sufficient database permissions for this operation. Please make sure that Rhetos Server process has db_owner role for the database.", exception);

            //=========================
            // Detect UNIQUE constraint:

            if (sqlException.Number == 2601)
            {
                // See the InterpretUniqueConstraint unit test for regex coverage.
                Regex messageParser = new Regex(@"^Cannot insert duplicate key row in object '(.+)' with unique index '(.+)'\.( The duplicate key value is \((.+)\)\.)?");
                var parts = messageParser.Match(sqlException.Message).Groups;

                var interpretedException = new UserException("It is not allowed to enter a duplicate record.", exception);

                interpretedException.Info["Constraint"] = "Unique";
                if (parts[1].Success)
                    interpretedException.Info["Table"] = parts[1].Value;
                if (parts[2].Success)
                    interpretedException.Info["ConstraintName"] = parts[2].Value;
                if (parts[4].Success)
                    interpretedException.Info["DuplicateValue"] = parts[4].Value;

                return interpretedException;
            }

            //=========================
            // Detect REFERENCE constraint:

            if (sqlException.Number == 547)
            {
                // See the InterpretReferenceConstraint unit test for regex coverage.
                Regex messageParser = new Regex(@"^(The )?(.+) statement conflicted with (the )?(.+) constraint [""'](.+)[""']. The conflict occurred in database [""'](.+)[""'], table [""'](.+?)[""'](, column [""'](.+?)[""'])?");
                var parts = messageParser.Match(sqlException.Message).Groups;
                string action = parts[2].Value ?? "";
                string constraintType = parts[4].Value ?? "";

                if (_referenceConstraintTypes.Contains(constraintType))
                {
                    UserException interpretedException = null;
                    if (action == "DELETE")
                        interpretedException = new UserException("It is not allowed to delete a record that is referenced by other records.", exception);
                    else if (action == "INSERT")
                        interpretedException = new UserException("It is not allowed to enter the record. The entered value references nonexistent record.", exception);
                    else if (action == "UPDATE")
                        interpretedException = new UserException("It is not allowed to edit the record. The entered value references nonexistent record.", exception);

                    if (interpretedException != null)
                    {
                        interpretedException.Info["Constraint"] = "Reference";
                        interpretedException.Info["Action"] = action;
                        if (parts[5].Success)
                            interpretedException.Info["ConstraintName"] = parts[5].Value; // The FK constraint name is ambiguous: The error does not show the schema name and the base table that the INSERT or UPDATE actually happened.
                        if (parts[7].Success)
                            interpretedException.Info[action == "DELETE" ? "DependentTable" : "ReferencedTable"] = parts[7].Value;
                        if (parts[9].Success)
                            interpretedException.Info[action == "DELETE" ? "DependentColumn" : "ReferencedColumn"] = parts[9].Value;

                        return interpretedException;
                    }
                }
            }

            return null;
        }