Ejemplo n.º 1
0
        public TownCrier()
        {
            string value = ConfigurationManager.AppSettings["FailureType"] ?? "none";

            _failureMode = (FailureType)Enum.Parse(typeof(FailureType), value, true);

            if (_failureMode == FailureType.FailToCreate)
                throw new InvalidOperationException("TownCrier was configured to fail on create");

            _timer = new System.Timers.Timer(1000)
                {
                    AutoReset = true
                };

            int loopCount = 0;
            _timer.Elapsed += (sender, eventArgs) =>
                {
                    Console.WriteLine(DateTime.Now);
                    loopCount++;

                    if (_failureMode == FailureType.CrashAfterStart && loopCount > 10)
                    {
                        _failureMode = FailureType.None;

                        ThreadPool.QueueUserWorkItem(x =>
                            {
                                throw new InvalidOperationException("TownCrier was configured to fail after startup");
                            });
                    }
                };
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HystrixRuntimeException"/> class with details about
 /// the cause and source of the error.
 /// </summary>
 /// <param name="failureCause"></param>
 /// <param name="commandType"></param>
 /// <param name="message"></param>
 /// <param name="innerException"></param>
 /// <param name="fallbackException"></param>
 public HystrixRuntimeException(FailureType failureCause, Type commandType, string message, Exception innerException, Exception fallbackException)
     : base(message, innerException)
 {
     FailureCause = failureCause;
     CommandType = commandType;
     FallbackException = fallbackException;
     CallingThreadStackTrace = ExceptionThreadingUtility.GetCallingThreadStack();
 }
Ejemplo n.º 3
0
 public ScenarioFailure(string id, FailureType type, int checkMonths, object value, string failureText, int monthsOfFailure)
 {
     this.ID = id;
     this.Type = type;
     this.CheckMonths = checkMonths;
     this.Value = value;
     this.FailureText = failureText;
     this.MonthsOfFailure = monthsOfFailure;
 }
 public ScenarioFailure(
     string id,
     FailureType type,
     int checkMonths,
     object value,
     string failureText,
     int monthsOfFailure)
 {
     ID = id;
     Type = type;
     CheckMonths = checkMonths;
     Value = value;
     FailureText = failureText;
     MonthsOfFailure = monthsOfFailure;
 }
Ejemplo n.º 5
0
    internal Transform GetFailureParticleSystemFromPool(FailureType failType)
    {
        List <Transform> pool = particleSystemPool[failType];

        if (pool.Count > 0)
        {
            Transform result = pool[0];
            pool.RemoveAt(0);
            result.gameObject.SetActive(true);
            return(result);
        }
        else
        {
            return((Transform)GameObject.Instantiate(GetParticleSystemPrefab(failType)));
        }
    }
Ejemplo n.º 6
0
        /// <summary>
        /// The logic for unchecking dependent options in this menu system isn't quite right, but it's fine for now.
        /// </summary>
        private void EnableMenuItem_Click(object sender, EventArgs e)
        {
            CheckForUpdate();

            MenuItem menuItem = (sender as MenuItem);

            if (menuItem.Text == enablePluginMenuItem.Text)
            {
                // Enable or disable children menu items
                menuItem.Checked = !menuItem.Checked;
                pluginEnabled    = enablePluginMenuItem.Checked;

                for (int i = 1; i < rootMenuItem.MenuItems.Count - 3; i++)
                {
                    rootMenuItem.MenuItems[i].Enabled = pluginEnabled;
                }
            }
            else if (failures.ContainsKey(menuItem.Text))
            {
                // Change the current failure type
                string failure = menuItem.Text;
                failureType = failures[failure];

                foreach (MenuItem item in failureTypeMenuItems)
                {
                    item.Checked = false;
                }

                menuItem.Checked = true;
            }
            else if (services.ContainsKey(menuItem.Text))
            {
                // Select which services to block
                string serviceName = menuItem.Text;
                menuItem.Checked = !menuItem.Checked;

                // Toggle residence in blocked host list
                if (menuItem.Checked)
                {
                    AddBlockedService(services[serviceName]);
                }
                else
                {
                    RemoveBlockedService(services[serviceName]);
                }
            }
        }
Ejemplo n.º 7
0
        private void UpdateFailureCount(Rock.CMS.User user, FailureType failureType)
        {
            DateTime FirstAttempt = (failureType == FailureType.Password ?
                                     user.FailedPasswordAttemptWindowStart :
                                     user.FailedPasswordAnswerAttemptWindowStart) ?? DateTime.MinValue;

            int attempts = (failureType == FailureType.Password ?
                            user.FailedPasswordAttemptCount :
                            user.FailedPasswordAnswerAttemptCount) ?? 0;

            TimeSpan window = new TimeSpan(0, passwordAttemptWindow, 0);

            if (DateTime.Now.CompareTo(FirstAttempt.Add(window)) < 0)
            {
                // Attempt is within window
                attempts++;
                if (attempts >= MaxInvalidPasswordAttempts)
                {
                    user.IsLockedOut       = true;
                    user.LastLockedOutDate = DateTime.Now;
                }

                if (failureType == FailureType.Password)
                {
                    user.FailedPasswordAttemptCount = attempts;
                }
                else
                {
                    user.FailedPasswordAnswerAttemptCount = attempts;
                }
            }
            else
            {
                // Attempt is outside window
                if (failureType == FailureType.Password)
                {
                    user.FailedPasswordAttemptCount       = 1;
                    user.FailedPasswordAttemptWindowStart = DateTime.Now;
                }
                else
                {
                    user.FailedPasswordAnswerAttemptCount       = 1;
                    user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now;
                }
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Update password and answer failure information.
        /// </summary>
        /// <param name="username">User name.</param>
        /// <param name="failureType">Type of failure</param>
        /// <remarks></remarks>
        private void UpdateFailureCount(IObjectScope objScope, Employee e, FailureType failureType)
        {
            int failureCount = 0;

            objScope.Transaction.Begin();
            if (failureType == FailureType.Password)
            {
                failureCount = e.FailedPasswordAttemptCount;
                if (failureCount == 0 ||
                    DateTime.Now > e.FailedPasswordAttemptWindowStart.AddMinutes(passwordAttemptWindow))
                {
                    e.FailedPasswordAttemptCount       = 1;
                    e.FailedPasswordAttemptWindowStart = DateTime.Now;
                }
            }
            else if (failureType == FailureType.PasswordAnswer)
            {
                failureCount = e.FailedPasswordAnswerAttemptCount;
                if (failureCount == 0 ||
                    DateTime.Now > e.FailedPasswordAnswerAttemptWindowStart.AddMinutes(passwordAttemptWindow))
                {
                    e.FailedPasswordAnswerAttemptCount       = 1;
                    e.FailedPasswordAnswerAttemptWindowStart = DateTime.Now;
                }
            }
            failureCount++;
            if (failureCount >= maxInvalidPasswordAttempts)
            {
                e.IsLockedOut       = true;
                e.LastLockedOutDate = DateTime.Now;
            }
            else
            {
                if (failureType == FailureType.Password)
                {
                    e.FailedPasswordAttemptCount = failureCount;
                }
                else if (failureType == FailureType.PasswordAnswer)
                {
                    e.FailedPasswordAnswerAttemptCount = failureCount;
                }
            }
            objScope.Transaction.Commit();
        }
Ejemplo n.º 9
0
        public ConeTestFailure(ITestName testName, Exception error, FailureType failureType)
        {
            TestName = testName.Name;
            Context = testName.Context;
            FailureType = failureType;

            var testError = Unwrap(error);
            StackFrames = GetNestedStackFrames(testError)
                .Where(ShouldIncludeFrame)
                .Select(x => new ConeStackFrame(x))
                .ToArray();

            var expectationFailed = testError as CheckFailed;
            if(expectationFailed != null)
                Errors = expectationFailed.Failures.ToArray();
            else
                Errors = new [] {
                    new FailedExpectation(testError.Message)
                };
        }
        /// <summary>
        /// Update password and answer failure information.
        /// </summary>
        /// <param name="username">User name.</param>
        /// <param name="failureType">Type of failure</param>
        /// <remarks></remarks>
        private void UpdateFailureCount(string username, FailureType failureType)
        {
            SqlConnection sqlConnection = new SqlConnection(connectionString);
            SqlCommand    sqlCommand    = new SqlCommand("Users_Sel_ByUserName", sqlConnection);

            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Parameters.Add("@failureType", SqlDbType.Int, 0).Value = failureType;
            sqlCommand.Parameters.Add("@passwordAttempWindow", SqlDbType.DateTime, 0).Value  = passwordAttemptWindow;
            sqlCommand.Parameters.Add("@maxInvalidPasswordAttempts", SqlDbType.Int, 0).Value = maxInvalidPasswordAttempts;
            sqlCommand.Parameters.Add("@userName", SqlDbType.NVarChar, 255).Value            = username;
            sqlCommand.Parameters.Add("@applicationName", SqlDbType.NVarChar, 255).Value     = applicationName;

            try
            {
                sqlConnection.Open();
                sqlCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                //Add exception handling here.
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// Update password and answer failure information.
 /// </summary>
 /// <param name="username">User name.</param>
 /// <param name="failureType">Type of failure</param>
 /// <remarks></remarks>
 private void UpdateFailureCount(string username, FailureType failureType)
 {
     try
     {
         User u = _memberRepo.GetUserByName(username, _applicationName);
         if (u != null)
         {
             if (failureType == FailureType.Password)
             {
                 u.FailedPasswordAttemptCount++;
             }
             else
             {
                 u.FailedPasswordAnswerAttemptCount++;
             }
             _memberRepo.SaveUser(u);
         }
     }
     catch (Exception ex)
     {
         throw new MemberAccessException("Error processing membership data - " + ex.Message);
     }
 }
 private void SimulateFailure(int onIteration)
 {
     if (_iterations == onIteration &&
         _taskIdsToFail.FirstOrDefault(e => _taskId.StartsWith(e)) != null &&
         _taskIdsToFail.FirstOrDefault(e => _taskId.Equals(e + _maxRetryInRecovery)) == null &&
         _retryIndex < _totalNumberOfForcedFailures)
     {
         Logger.Log(Level.Warning,
                    "Simulating {0} failure for taskId {1}",
                    FailureType.IsEvaluatorFailure(_failureType) ? "evaluator" : "task",
                    _taskId);
         if (FailureType.IsEvaluatorFailure(_failureType))
         {
             // simulate evaluator failure
             Environment.Exit(1);
         }
         else
         {
             // simulate task failure
             throw new ArgumentNullException("Simulating task failure");
         }
     }
 }
Ejemplo n.º 13
0
		public ConeTestFailure(ITestName testName, Exception error, FailureType failureType, Func<StackFrame, bool> includeFrame) {
			TestName = testName.Name;
			Context = testName.Context;
			FailureType = failureType;

			var testError = Unwrap(error);
			StackFrames = GetNestedStackFrames(testError)
				.Where(includeFrame)
				.Select(x => new ConeStackFrame(x))
				.ToArray();

			var expectationFailed = testError as CheckFailed;
			if(expectationFailed != null)
			{
				ErrorsContext = expectationFailed.Context;
				Errors = expectationFailed.Failures;
			}
			else
			{
				ErrorsContext = string.Empty;
				Errors = new [] { new FailedExpectation(testError.Message) };
			}
		}
 public FailureEvent(string phoneNumber, FailureType failureType)
 {
     PhoneNumber = phoneNumber;
     FailureType = failureType;
 }
		/// <summary>
		/// A helper method that performs the checks and updates associated with
		/// password failure tracking.
		/// </summary>
		/// <param name="username"></param>
		/// <param name="failType"></param>
		void UpdateFailureCount(string username, FailureType failType)
		{
			DateTime windowStart = new DateTime();
			int failureCount = 0;

			using (SqliteConnection dbConn = new SqliteConnection(m_ConnectionString))
			{
				// Fetch user data from database
				using (SqliteCommand dbCommand = dbConn.CreateCommand())
				{
					dbCommand.CommandText = string.Format("SELECT \"FailedPasswordAttemptCount\", \"FailedPasswordAttemptWindowStart\", \"FailedPasswordAnswerAttemptCount\", \"FailedPasswordAnswerAttemptWindowStart\" FROM \"{0}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);

					AddParameter (dbCommand,"@Username", username);
					AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);

					try
					{
						dbConn.Open();
						dbCommand.Prepare();

						using (SqliteDataReader reader = dbCommand.ExecuteReader())
						{
							if (reader.HasRows)
							{
								reader.Read();

								if (failType.Equals(FailureType.Password))
								{
									failureCount = reader.GetInt32(0);
									windowStart = reader.GetDateTime(1);
								}
								else if (failType.Equals(FailureType.PasswordAnswer))
								{
									failureCount = reader.GetInt32(2);
									windowStart = reader.GetDateTime(3);
								}
							}
						}
					}
					catch (SqliteException e)
					{
						Trace.WriteLine(e.ToString());
						throw new ProviderException(Properties.Resources.ErrOperationAborted);
					}
					finally
					{
						if (dbConn != null)
							dbConn.Close();
					}
				}

				// Calculate failture count and update database
				using (SqliteCommand dbCommand = dbConn.CreateCommand())
				{
					DateTime windowEnd = windowStart.AddMinutes(m_PasswordAttemptWindow);

					try
					{
						if (failureCount == 0 || DateTime.Now > windowEnd)
						{
							// First password failure or outside of PasswordAttemptWindow. 
							// Start a new password failure count from 1 and a new window starting now.

							if (failType.Equals(FailureType.Password))
							{
								dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"FailedPasswordAttemptCount\" = @Count, \"FailedPasswordAttemptWindowStart\" = @WindowStart WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
							}
							else if (failType.Equals(FailureType.PasswordAnswer))
							{
								dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"FailedPasswordAnswerAttemptCount\" = @Count, \"FailedPasswordAnswerAttemptWindowStart\" = @WindowStart WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
							}

							AddParameter (dbCommand,"@Count", 1);
							AddParameter (dbCommand,"@WindowStart", DateTime.Now);
							AddParameter (dbCommand,"@Username", username);
							AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);

							if (dbCommand.ExecuteNonQuery() < 0)
								throw new ProviderException(Properties.Resources.ErrCantUpdateFailtureCountAndWindowStart);
						}
						else
						{
							failureCount++;

							if (failureCount >= m_MaxInvalidPasswordAttempts)
							{
								// Password attempts have exceeded the failure threshold. Lock out
								// the user.
								dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"IsLockedOut\" = @IsLockedOut, \"LastLockedOutDate\" = @LastLockedOutDate WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);

								AddParameter (dbCommand,"@IsLockedOut", true);
								AddParameter (dbCommand,"@LastLockedOutDate", DateTime.Now);
								AddParameter (dbCommand,"@Username", username);
								AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);

								if (dbCommand.ExecuteNonQuery() < 0)
									throw new ProviderException(string.Format(Properties.Resources.ErrCantLogoutUser, username));
							}
							else
							{
								// Password attempts have not exceeded the failure threshold. Update
								// the failure counts. Leave the window the same.
								if (failType.Equals(FailureType.Password))
								{
									dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"FailedPasswordAttemptCount\" = @Count WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
								}
								else if (failType.Equals(FailureType.PasswordAnswer))
								{
									dbCommand.CommandText = string.Format("UPDATE \"{0}\" SET \"FailedPasswordAnswerAttemptCount\" = @Count WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", m_TableName);
								}

								AddParameter (dbCommand,"@Count", failureCount);
								AddParameter (dbCommand,"@Username", username);
								AddParameter (dbCommand,"@ApplicationName", m_ApplicationName);

								if (dbCommand.ExecuteNonQuery() < 0)
									throw new ProviderException(Properties.Resources.ErrCantUpdateFailtureCount);
							}
						}
					}
					catch (SqliteException e)
					{
						Trace.WriteLine(e.ToString());
						throw new ProviderException(Properties.Resources.ErrOperationAborted);
					}
					finally
					{
						if (dbConn != null)
							dbConn.Close();
					}
				}
			}
		}
    private void UpdateFailureCount(String username, FailureType failureType)
    {
        DateTime windowStart;
        DateTime windowEnd;
        int      failureCount;

        using (Session session = XpoHelper.GetNewSession()) {
            XpoUser user = session.FindObject <XpoUser>(new GroupOperator(
                                                            GroupOperatorType.And,
                                                            new BinaryOperator("ApplicationName", ApplicationName, BinaryOperatorType.Equal),
                                                            new BinaryOperator("UserName", username, BinaryOperatorType.Equal)));

            switch (failureType)
            {
            case FailureType.Password:
                failureCount = user.FailedPasswordAttemptCount;
                windowStart  = user.FailedPasswordAttemptWindowStart;
                windowEnd    = windowStart.AddMinutes(PasswordAttemptWindow);

                user.FailedPasswordAttemptWindowStart = DateTime.Now;

                if (DateTime.Now > windowEnd)
                {
                    user.FailedPasswordAttemptCount = 1;
                }
                else
                {
                    user.FailedPasswordAttemptCount++;
                }

                if (user.FailedPasswordAttemptCount >= MaxInvalidPasswordAttempts)
                {
                    if (!user.IsLockedOut)
                    {
                        user.LastLockedOutDate = DateTime.Now;
                        user.IsLockedOut       = true;
                    }
                }
                break;

            case FailureType.PasswordAnswer:
                failureCount = user.FailedPasswordAnswerAttemptCount;
                windowStart  = user.FailedPasswordAnswerAttemptWindowStart;
                windowEnd    = windowStart.AddMinutes(PasswordAttemptWindow);

                user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now;

                if (DateTime.Now > windowEnd)
                {
                    user.FailedPasswordAnswerAttemptCount = 1;
                }
                else
                {
                    user.FailedPasswordAnswerAttemptCount++;
                }

                if (user.FailedPasswordAnswerAttemptCount >= MaxInvalidPasswordAttempts)
                {
                    if (!user.IsLockedOut)
                    {
                        user.LastLockedOutDate = DateTime.Now;
                        user.IsLockedOut       = true;
                    }
                }
                break;
            }
            user.Save();
        }
    }
 public void UpdateFailureCount(string username, FailureType failureType)
 {
     using (var session = sessionFactory.OpenSession())
     {
         using (var trans = session.BeginTransaction())
         {
             IList uList = session.CreateCriteria(typeof(User))
                 .Add(Expression.Eq("UserName", username))
                 .Add(Expression.Eq("ApplicationName", _config.applicationName))
                 .List();
             foreach (User u in uList)
             {
                 if (failureType == FailureType.Password)
                 {
                     u.FailedPasswordAttemptCount++;
                 }
                 else
                 {
                     u.FailedPasswordAnswerAttemptCount++;
                 }
                 session.Save(u);
             }
             trans.Commit();
         }
     }
 }
Ejemplo n.º 18
0
 public void AuthenticationFailureEventHandle(JObject challenge, FailureType type)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 19
0
 public override Exception OnError <T>(HystrixCommand <T> commandInstance, FailureType failureType, Exception e)
 {
     this.endExecuteFailureException = e;
     this.endExecuteFailureType      = failureType;
     return(base.OnError(commandInstance, failureType, e));
 }
        internal void AddFailure(IEnumerable <SpecificationFailure <TCandidate> > failures, FailureType failureType)
        {
            StringBuilder messageBuilder = failureType == FailureType.Error ? _errorMessageBuilder : _warningMessageBuilder;
            List <SpecificationFailure <TCandidate> > addedFailures = failureType == FailureType.Error ? _errors : _warnings;

            var failuresToAdd = failures.Where(failure => !addedFailures.Any(addedFailure => addedFailure.Equals(failure)));

            foreach (SpecificationFailure <TCandidate> failure in failuresToAdd)
            {
                messageBuilder.AppendMessage(failure.ValidationMessage);
            }

            addedFailures.AddRange(failuresToAdd);
        }
Ejemplo n.º 21
0
 public Failure(FailureType failure, int device, DateTime date)
 {
     this.failure = (FailureType)failure;
     this.device  = device;
     this.date    = date;
 }
Ejemplo n.º 22
0
        private void UpdateFailureCount(Guid UserId, FailureType failureType)
        {
            DataTable dt = SecurityAdapters.MembershipAdapter.GetFailureInfo(UserId);

            // Variables to store failure information
            int failureCount = 0;	// Maintain the count of failure
            DateTime windowStart = DateTime.Now;	// Maintains the last failure Start

            // Initilize the values if information found
            if (dt.Rows.Count > 0)
            {
                // Incase of Pasword mismatch
                if (failureType == FailureType.Password)
                {
                    if (DBNull.Value != dt.Rows[0]["FailedPasswordAttemptCount"])
                        failureCount = Convert.ToInt32(dt.Rows[0]["FailedPasswordAttemptCount"]);
                    if (DBNull.Value != dt.Rows[0]["FailedPasswordAttemptWindowStart"])
                        windowStart = Convert.ToDateTime(dt.Rows[0]["FailedPasswordAttemptWindowStart"]);
                }
                // Incase of Password Answer mismatch
                if (failureType == FailureType.PasswordAnswer)
                {
                    if (DBNull.Value != dt.Rows[0]["FailedPasswordAnswerAttemptCount"])
                        failureCount = Convert.ToInt32(dt.Rows[0]["FailedPasswordAnswerAttemptCount"]);
                    if (DBNull.Value != dt.Rows[0]["FailedPasswordAnswerAttemptWindowStart"])
                        windowStart = Convert.ToDateTime(dt.Rows[0]["FailedPasswordAnswerAttemptWindowStart"]);
                }
            }

            // Get interval PasswordAttemptWindow close
            DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow);

            // Check if this is the first failure or outside of PasswordAttemptWindow.
            if (failureCount == 0 || DateTime.Now > windowEnd)
            {	// This is either the first failure or outside of PasswordAttemptWindow.

                int rowsAffected = 0;
                // Incase of Pasword mismatch
                if (failureType == FailureType.Password)
                {
                    rowsAffected = SecurityAdapters.MembershipAdapter.UpdateFailedPassword(1, windowStart, UserId);
                }
                // Incase of Password Answer mismatch
                if (failureType == FailureType.PasswordAnswer)
                {
                    rowsAffected = SecurityAdapters.MembershipAdapter.UpdateFailedPasswordAsnwer(1, windowStart, UserId);
                }

                if (rowsAffected < 0)
                {	// Update has failed
                    throw new ProviderException("Unable to update failure count and window start.");
                }
            }
            else
            {	// This is not the first failure
                // Check if the attempt exeeds the max attempt threshold
                if (failureCount++ >= MaxInvalidPasswordAttempts)
                {	// Password attempts have exceeded the failure threshold.
                    if (SecurityAdapters.MembershipAdapter.LockoutUser(UserId) < 0)
                    {	// Update has failed
                        throw new ProviderException("Unable to lock out user.");
                    }
                }
                else
                {	// Password attempts have not exceeded the failure threshold.
                    int rowsAffected = 0;
                    // Incase of Pasword mismatch
                    if (failureType == FailureType.Password)
                    {
                        rowsAffected = SecurityAdapters.MembershipAdapter.UpdateFailedPassword(failureCount, windowStart, UserId);
                    }
                    // Incase of Password Answer mismatch
                    if (failureType == FailureType.PasswordAnswer)
                    {
                        rowsAffected = SecurityAdapters.MembershipAdapter.UpdateFailedPasswordAsnwer(failureCount, windowStart, UserId);
                    }
                    if (rowsAffected < 0)
                    {	// Update has failed
                        throw new ProviderException("Unable to update failure count.");
                    }
                }
            }
        }
 public CommandRuntimeException(FailureType failure, string message, string commandName, Exception ex, Exception fallbackException) : base(message, ex)
 {
     this.FailureCause = failure;
     this.FallbackException = fallbackException;
     this.CommandName = commandName;
 }
Ejemplo n.º 24
0
 public FailureMessage(FailureType type, Exception exception)
 {
     this.Type = type;
     this.Exception = exception;
 }
 private void UpdateFailureCount(String userName, FailureType failureType)
 {
     switch (failureType)
     {
         case FailureType.PASSWORD:
             UpdateFailureForPassword(userName);
             break;
         case FailureType.PASSWORD_ANSWER:
             UpdateFailureForPasswordAnswer(userName);
             break;
     }
 }
        /// <summary>
        /// A helper method that performs the checks and updates associated with password failure tracking.
        /// </summary>
        /// <param name="username">name of the user that is failing to specify a valid password.</param>
        /// <param name="failureType">type of failure to record.</param>
        private void UpdateFailureCount(ISession session, ITransaction tx, string username, FailureType failureType)
        {
            // Get user record associated to the given user name.
            User user = UserLogic.GetUser(session, username);
            if (null != user)
            {
                // Update the failure information for the given user in the data store.
                DateTime windowStart = DateTime.Now;
                int failureCount = 0;
                try
                {
                    // First determine the type of update we need to do and get the relevant details.
                    switch (failureType)
                    {
                        case FailureType.Password:
                            windowStart = user.FailedPasswordAttemptWindowStart;
                            failureCount = user.FailedPasswordAttemptCount;
                            break;
                        case FailureType.PasswordAnswer:
                            windowStart = user.FailedPasswordAnswerAttemptWindowStart;
                            failureCount = user.FailedPasswordAnswerAttemptCount;
                            break;
                    }

                    // Then determine if the threashold has been exeeded.
                    DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow);
                    if ((0 == failureCount) || DateTime.Now > windowEnd)
                    {
                        // First password failure or outside of window, start new password failure count from 1
                        // and a new window start.
                        switch (failureType)
                        {
                            case FailureType.Password:
                                user.FailedPasswordAttemptWindowStart = DateTime.Now;
                                user.FailedPasswordAttemptCount = 1;
                                break;
                            case FailureType.PasswordAnswer:
                                user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now;
                                user.FailedPasswordAnswerAttemptCount = 1;
                                break;
                        }
                    }
                    else
                    {
                        // Track failures.
                        failureCount++;
                        if (failureCount >= MaxInvalidPasswordAttempts)
                        {
                            // Password attempts have exceeded the failure threshold. Lock out the user.
                            user.IsLockedOut = true;
                            user.LastLockedOutDate = DateTime.Now;
                        }
                        else
                        {
                            switch (failureType)
                            {
                                case FailureType.Password:
                                    user.FailedPasswordAttemptCount = failureCount;
                                    break;
                                case FailureType.PasswordAnswer:
                                    user.FailedPasswordAnswerAttemptCount = failureCount;
                                    break;
                            }
                        }
                    }

                    // Persist the changes.
                    user.Save(session, tx);
                }
                catch (Exception ex)
                {
                    throw new ProviderException("Unable to Update UpdateFailureCount", ex);
                }

            }
        }
        /// <summary>
        /// A helper method that performs the checks and updates associated with password failure tracking.
        /// </summary>
        /// <param name="username">name of the user that is failing to specify a valid password.</param>
        /// <param name="failureType">type of failure to record.</param>
        private void UpdateFailureCount(string username, FailureType failureType)
        {
            // Get user record associated to the given user name.
            AspnetUser user = _aspnetUserService.GetAspnetUser(username);
            AspnetMembership membership = _aspnetMembershipService.GetMembership(user.UserId);
            if (null != membership)
            {
                // Update the failure information for the given user in the data store.
                DateTime windowStart = DateTime.Now;
                int failureCount = 0;
                try
                {
                    // First determine the type of update we need to do and get the relevant details.
                    switch (failureType)
                    {
                        case FailureType.Password:
                            windowStart = membership.FailedPasswordAttemptWindowStart;
                            failureCount = membership.FailedPasswordAttemptCount;
                            break;
                        case FailureType.PasswordAnswer:
                            windowStart = membership.FailedPasswordAnswerAttemptWindowStart;
                            failureCount = membership.FailedPasswordAnswerAttemptCount;
                            break;
                    }

                    // Then determine if the threashold has been exeeded.
                    DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow);
                    if ((0 == failureCount) || DateTime.Now > windowEnd)
                    {
                        // First password failure or outside of window, start new password failure count from 1
                        // and a new window start.
                        switch (failureType)
                        {
                            case FailureType.Password:
                                membership.FailedPasswordAttemptWindowStart = DateTime.Now;
                                membership.FailedPasswordAttemptCount = 1;
                                break;
                            case FailureType.PasswordAnswer:
                                membership.FailedPasswordAnswerAttemptWindowStart = DateTime.Now;
                                membership.FailedPasswordAnswerAttemptCount = 1;
                                break;
                        }
                    }
                    else
                    {
                        // Track failures.
                        failureCount++;
                        if (failureCount >= MaxInvalidPasswordAttempts)
                        {
                            // Password attempts have exceeded the failure threshold. Lock out the user.
                            membership.IsLockedOut = true;
                            membership.LastLockoutDate = DateTime.Now;
                        }
                        else
                        {
                            switch (failureType)
                            {
                                case FailureType.Password:
                                    membership.FailedPasswordAttemptCount = failureCount;
                                    break;
                                case FailureType.PasswordAnswer:
                                    membership.FailedPasswordAnswerAttemptCount = failureCount;
                                    break;
                            }
                        }
                    }

                    // Persist the changes.
                    _aspnetMembershipService.UpdateMembership(membership);
                }
                catch (Exception ex)
                {
                    if (WriteExceptionsToEventLog)
                    {
                        WriteToEventLog(ex, "UpdateFailureCount");

                        throw ExceptionUtil.NewProviderException(this, Resources.User_UnableToUpdateFailureCount, ex);
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// A helper method that performs the checks and updates associated with
        /// password failure tracking.
        /// </summary>
        /// <param name="username"></param>
        /// <param name="failType"></param>
        private void UpdateFailureCount(string username, FailureType failType)
        {
            DateTime windowStart = new DateTime();
            int failureCount = 0;

            using (NpgsqlConnection dbConn = new NpgsqlConnection(m_connectionString))
            {
                // Fetch user data from database
                using (NpgsqlCommand dbCommand = dbConn.CreateCommand())
                {
                    dbCommand.CommandText = string.Format(CultureInfo.InvariantCulture, "SELECT \"FailedPasswordAttemptCount\", \"FailedPasswordAttemptWindowStart\", \"FailedPasswordAnswerAttemptCount\", \"FailedPasswordAnswerAttemptWindowStart\" FROM \"{0}\" WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", s_tableName);

                    dbCommand.Parameters.Add("@Username", NpgsqlDbType.Varchar, 255).Value = username;
                    dbCommand.Parameters.Add("@ApplicationName", NpgsqlDbType.Varchar, 255).Value = m_applicationName;

                    try
                    {
                        dbConn.Open();
                        dbCommand.Prepare();

                        using (NpgsqlDataReader reader = dbCommand.ExecuteReader())
                        {
                            if (reader.HasRows)
                            {
                                reader.Read();

                                if (failType.Equals(FailureType.Password))
                                {
                                    failureCount = reader.IsDBNull(0) ? 0 : reader.GetInt32(0);
                                    windowStart = reader.IsDBNull(1) ? DateTime.MinValue : reader.GetDateTime(1);
                                }
                                else if (failType.Equals(FailureType.PasswordAnswer))
                                {
                                    failureCount = reader.IsDBNull(2) ? 0 : reader.GetInt32(2);
                                    windowStart = reader.IsDBNull(3) ? DateTime.MinValue : reader.GetDateTime(3);
                                }
                            }
                        }
                    }
                    catch (NpgsqlException e)
                    {
                        Trace.WriteLine(e.ToString());

                        if (dbConn != null)
                            dbConn.Close();

                        throw new ProviderException(Properties.Resources.ErrOperationAborted);
                    }
                }

                // Calculate failture count and update database
                using (NpgsqlCommand dbCommand = dbConn.CreateCommand())
                {
                    DateTime windowEnd = windowStart.AddMinutes(m_passwordAttemptWindow);

                    try
                    {
                        if (failureCount == 0 || DateTime.Now > windowEnd)
                        {
                            // First password failure or outside of PasswordAttemptWindow. 
                            // Start a new password failure count from 1 and a new window starting now.

                            if (failType.Equals(FailureType.Password))
                            {
                                dbCommand.CommandText = string.Format(CultureInfo.InvariantCulture, "UPDATE \"{0}\" SET \"FailedPasswordAttemptCount\" = @Count, \"FailedPasswordAttemptWindowStart\" = @WindowStart WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", s_tableName);
                            }
                            else if (failType.Equals(FailureType.PasswordAnswer))
                            {
                                dbCommand.CommandText = string.Format(CultureInfo.InvariantCulture, "UPDATE \"{0}\" SET \"FailedPasswordAnswerAttemptCount\" = @Count, \"FailedPasswordAnswerAttemptWindowStart\" = @WindowStart WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", s_tableName);
                            }

                            dbCommand.Parameters.Add("@Count", NpgsqlDbType.Integer).Value = 1;
                            dbCommand.Parameters.Add("@WindowStart", NpgsqlDbType.TimestampTZ).Value = DateTime.Now;
                            dbCommand.Parameters.Add("@Username", NpgsqlDbType.Varchar, 255).Value = username;
                            dbCommand.Parameters.Add("@ApplicationName", NpgsqlDbType.Varchar, 255).Value = m_applicationName;

                            if (dbCommand.ExecuteNonQuery() < 0)
                                throw new ProviderException(Properties.Resources.ErrCantUpdateFailtureCountAndWindowStart);
                        }
                        else
                        {
                            failureCount++;

                            if (failureCount >= m_maxInvalidPasswordAttempts)
                            {
                                // Password attempts have exceeded the failure threshold. Lock out
                                // the user.
                                dbCommand.CommandText = string.Format(CultureInfo.InvariantCulture, "UPDATE \"{0}\" SET \"IsLockedOut\" = @IsLockedOut, \"LastLockedOutDate\" = @LastLockedOutDate WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", s_tableName);

                                dbCommand.Parameters.Add("@IsLockedOut", NpgsqlDbType.Boolean).Value = true;
                                dbCommand.Parameters.Add("@LastLockedOutDate", NpgsqlDbType.TimestampTZ).Value = DateTime.Now;
                                dbCommand.Parameters.Add("@Username", NpgsqlDbType.Varchar, 255).Value = username;
                                dbCommand.Parameters.Add("@ApplicationName", NpgsqlDbType.Varchar, 255).Value = m_applicationName;

                                if (dbCommand.ExecuteNonQuery() < 0)
                                    throw new ProviderException(string.Format(CultureInfo.InvariantCulture, Properties.Resources.ErrCantLogoutUser, username));
                            }
                            else
                            {
                                // Password attempts have not exceeded the failure threshold. Update
                                // the failure counts. Leave the window the same.
                                if (failType.Equals(FailureType.Password))
                                {
                                    dbCommand.CommandText = string.Format(CultureInfo.InvariantCulture, "UPDATE \"{0}\" SET \"FailedPasswordAttemptCount\" = @Count WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", s_tableName);
                                }
                                else if (failType.Equals(FailureType.PasswordAnswer))
                                {
                                    dbCommand.CommandText = string.Format(CultureInfo.InvariantCulture, "UPDATE \"{0}\" SET \"FailedPasswordAnswerAttemptCount\" = @Count WHERE \"Username\" = @Username AND \"ApplicationName\" = @ApplicationName", s_tableName);
                                }

                                dbCommand.Parameters.Add("@Count", NpgsqlDbType.Integer).Value = failureCount;
                                dbCommand.Parameters.Add("@Username", NpgsqlDbType.Varchar, 255).Value = username;
                                dbCommand.Parameters.Add("@ApplicationName", NpgsqlDbType.Varchar, 255).Value = m_applicationName;

                                if (dbCommand.ExecuteNonQuery() < 0)
                                    throw new ProviderException(Properties.Resources.ErrCantUpdateFailtureCount);
                            }
                        }
                    }
                    catch (NpgsqlException e)
                    {
                        Trace.WriteLine(e.ToString());
                        throw new ProviderException(Properties.Resources.ErrOperationAborted);
                    }
                    finally
                    {
                        if (dbConn != null)
                            dbConn.Close();
                    }
                }
            }
        }
Ejemplo n.º 29
0
 private void updateFailureCount(Users user, FailureType failureType)
 {
     DateTime windowStart = new DateTime();
     int failureCount = 0;
     switch (failureType)
     {
         case FailureType.Password:
             failureCount = user.FailedPasswordAttemptCount;
             windowStart = user.FailedPasswordAttemptWindowStart;
             break;
         case FailureType.PasswordAnswer:
             failureCount = user.FailedPasswordAnswerAttemptCount;
             windowStart = user.FailedPasswordAnswerAttemptWindowStart;
             break;
     }
     DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow);
     if (failureCount == 0 || DateTime.Now > windowEnd)
     {
         switch (failureType)
         {
             case FailureType.Password:
                 user.FailedPasswordAttemptCount = 1;
                 user.FailedPasswordAttemptWindowStart = DateTime.Now;
                 break;
             case FailureType.PasswordAnswer:
                 user.FailedPasswordAnswerAttemptCount = 1;
                 user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now;
                 break;
         }
     }
     else if (++failureCount >= MaxInvalidPasswordAttempts)
     {
         user.IsLockedOut = true;
         switch (failureType)
         {
             case FailureType.Password:
                 user.FailedPasswordAttemptCount = failureCount;
                 user.FailedPasswordAttemptWindowStart = windowEnd;
                 break;
             case FailureType.PasswordAnswer:
                 user.FailedPasswordAnswerAttemptCount = failureCount;
                 user.FailedPasswordAnswerAttemptWindowStart = windowEnd;
                 break;
         }
         user.LastLockedOutDate = DateTime.Now;
     }
     else
     {
         switch (failureType)
         {
             case FailureType.Password:
                 user.FailedPasswordAttemptCount = failureCount;
                 break;
             case FailureType.PasswordAnswer:
                 user.FailedPasswordAnswerAttemptCount = failureCount;
                 break;
         }
     }
     _reportingRepository.Update<Users>(user, new { Id = user.Id });
 }
 /// <summary>
 /// Update password and answer failure information.
 /// </summary>
 /// <param name="username">User name.</param>
 /// <param name="failureType">Type of failure</param>
 /// <remarks></remarks>
 private void UpdateFailureCount(string username, FailureType failureType)
 {
     try
     {
         User u = UserRepo.GetUserByName(username, _applicationName);
         if (u != null)
         {
             if (failureType == FailureType.Password) u.FailedPasswordAttemptCount++;
             else u.FailedPasswordAnswerAttemptCount++;
             UserRepo.SaveUser(u);
         }
     }
     catch (Exception ex)
     {
         throw new MemberAccessException("Error processing membership data - " + ex.Message);
     }
 }
Ejemplo n.º 31
0
        public ActionResult ReserveFail(FailureType id, string company)
        {
            string message = string.Empty;
            ViewBag.company = company;

            switch (id)
            {
                case FailureType.TimeOut:
                    message = "The time limit for completing this reservation request has expired.";
                    break;
                case FailureType.Exception:
                    message = "An error occured while processing your request. Please try again later.";
                    break;
                case FailureType.AlreadyBooked:
                    message = "Sorry, this reservation is no longer available. Please click <a href='/online'>Search Again</a> to choose another available reservation.";
                    break;
                case FailureType.ReservationNotFound:
                    message = "Sorry, No reservation found.";
                    break;
                case FailureType.ReservationLocked:
                    message = "Sorry, You cannot edit this reservation.";
                    break;
                case FailureType.NotOnlineReservation:
                    message = "This reservation is not created online.";
                    break;
                default:
                    break;
            }

            return View(model: message);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Update password and answer failure information.
        /// </summary>
        /// <param name="username">User name.</param>
        /// <param name="failureType">Type of failure</param>
        /// <remarks></remarks>
        private void UpdateFailureCount(string username, FailureType failureType)
        {
            SqlConnection sqlConnection = new SqlConnection(connectionString);
            SqlCommand sqlCommand = new SqlCommand("Users_Sel_ByUserName", sqlConnection);

            sqlCommand.CommandType = CommandType.StoredProcedure;
            sqlCommand.Parameters.Add("@failureType", SqlDbType.Int, 0).Value = failureType;
            sqlCommand.Parameters.Add("@passwordAttempWindow", SqlDbType.DateTime, 0).Value = passwordAttemptWindow;
            sqlCommand.Parameters.Add("@maxInvalidPasswordAttempts", SqlDbType.Int, 0).Value = maxInvalidPasswordAttempts;
            sqlCommand.Parameters.Add("@userName", SqlDbType.NVarChar, 255).Value = username;
            sqlCommand.Parameters.Add("@applicationName", SqlDbType.NVarChar, 255).Value = applicationName;

            try
            {
                sqlConnection.Open();
                sqlCommand.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                //Add exception handling here.
            }
        }
Ejemplo n.º 33
0
 public Failure(FailureType type)
 {
     Type      = type;
     IsSerious = (int)Type % 2 == 0;
 }
Ejemplo n.º 34
0
 public CommandRuntimeException(FailureType failure, string commandName, string message, Exception ex, Exception fallbackException) : base(message, ex)
 {
     this.FailureCause      = failure;
     this.FallbackException = fallbackException;
     this.CommandName       = commandName;
 }
Ejemplo n.º 35
0
 public Failure(DateTime d, FailureType t)
 {
     FailureDate = d;
     FailureType = t;
 }
Ejemplo n.º 36
0
 public virtual Exception OnError(IHystrixInvokable commandInstance, FailureType failureType, Exception e)
 {
     return(e); // by default, just pass through
 }
Ejemplo n.º 37
0
 public static bool IsFailureSerious(FailureType failureType)
 {
     return(failureType == FailureType.UnexpectedShutdown ||
            failureType == FailureType.HardwareFailures);
 }
Ejemplo n.º 38
0
 public FailureObject(FailureType failureType, Range randomRange)
 {
     FailureType = failureType;
     RandomRage  = randomRange;
 }
        private void UpdateFailureCount(string username, FailureType failureType)
        {
            SystemUser user = this.ServicesContainerInstance.SystemUserServiceInstance.GetUserByLoginID(username);
            if (user != null)
            {
                DateTime now = DateTime.Now;
                int failedPasswordAttemptCount = 0;
                try
                {
                    switch (failureType)
                    {
                        case FailureType.Password:
                            now = user.FailedPwdAttemptWndStart.Value;
                            failedPasswordAttemptCount = user.FailedPwdAttemptCnt;
                            break;

                        case FailureType.PasswordAnswer:
                            now = user.FailedPwdAnsAttemptWndStart.Value;
                            failedPasswordAttemptCount = user.FailedPwdAnsAttemptCnt;
                            break;
                    }
                    DateTime time2 = now.AddMinutes(PasswordAttemptWindow);
                    if ((failedPasswordAttemptCount == 0) || (DateTime.Now > time2))
                    {
                        switch (failureType)
                        {
                            case FailureType.Password:
                                user.FailedPwdAttemptWndStart = DateTime.Now;
                                user.FailedPwdAttemptCnt = 1;
                                goto Label_00E7;

                            case FailureType.PasswordAnswer:
                                user.FailedPwdAnsAttemptWndStart = DateTime.Now;
                                user.FailedPwdAnsAttemptCnt = 1;
                                goto Label_00E7;
                        }
                    }
                    else
                    {
                        failedPasswordAttemptCount++;
                        if (failedPasswordAttemptCount >= MaxInvalidPasswordAttempts)
                        {
                            user.IsLockedOut = true;
                            user.LastLockedOutDate = DateTime.Now;
                        }
                        else
                        {
                            switch (failureType)
                            {
                                case FailureType.Password:
                                    user.FailedPwdAttemptCnt = failedPasswordAttemptCount;
                                    goto Label_00E7;

                                case FailureType.PasswordAnswer:
                                    user.FailedPwdAnsAttemptCnt = failedPasswordAttemptCount;
                                    goto Label_00E7;
                            }
                        }
                    }
                Label_00E7:
                    this.ServicesContainerInstance.SystemUserServiceInstance.SaveOrUpdate(user);
                }
                catch (Exception exception)
                {
                    throw NhibernateMembershipProviderExceptionUtil.NewProviderException(this,
                                                                                         SR.
                                                                                             User_UnableToUpdateFailureCount,
                                                                                         exception);
                }
            }
        }
Ejemplo n.º 40
0
        private void UpdateFailureCount( Rock.Models.Cms.User user, FailureType failureType )
        {
            DateTime FirstAttempt = (failureType == FailureType.Password ?
                user.FailedPasswordAttemptWindowStart :
                user.FailedPasswordAnswerAttemptWindowStart) ?? DateTime.MinValue;

            int attempts = (failureType == FailureType.Password ?
                user.FailedPasswordAttemptCount :
                user.FailedPasswordAnswerAttemptCount) ?? 0;

            TimeSpan window = new TimeSpan(0, passwordAttemptWindow, 0);
            if ( DateTime.Now.CompareTo( FirstAttempt.Add( window ) ) < 0 )
            {
                // Attempt is within window
                attempts++;
                if ( attempts >= MaxInvalidPasswordAttempts )
                {
                    user.IsLockedOut = true;
                    user.LastLockedOutDate = DateTime.Now;
                }

                if ( failureType == FailureType.Password )
                    user.FailedPasswordAttemptCount = attempts;
                else
                    user.FailedPasswordAnswerAttemptCount = attempts;
            }
            else
            {
                // Attempt is outside window
                if ( failureType == FailureType.Password )
                {
                    user.FailedPasswordAttemptCount = 1;
                    user.FailedPasswordAttemptWindowStart = DateTime.Now;
                }
                else
                {
                    user.FailedPasswordAnswerAttemptCount = 1;
                    user.FailedPasswordAnswerAttemptWindowStart = DateTime.Now;
                }
            }
        }
Ejemplo n.º 41
0
 public OmniCorePeripheralException(FailureType failureType, string message = null, Exception inner = null) : base(failureType, message, inner)
 {
 }
Ejemplo n.º 42
0
        /// <summary>
        /// Update password and answer failure information.
        /// </summary>
        /// <param name="username">User name.</param>
        /// <param name="failureType">Type of failure</param>
        /// <remarks></remarks>
        private void UpdateFailureCount(IObjectScope objScope, Employee e, FailureType failureType)
        {
            int failureCount = 0;
            objScope.Transaction.Begin();
            if (failureType == FailureType.Password)
            {
                failureCount = e.FailedPasswordAttemptCount;
                if (failureCount == 0
                    || DateTime.Now > e.FailedPasswordAttemptWindowStart.AddMinutes(passwordAttemptWindow))
                {
                    e.FailedPasswordAttemptCount = 1;
                    e.FailedPasswordAttemptWindowStart = DateTime.Now;
                }

            }
            else if(failureType == FailureType.PasswordAnswer)
            {
                failureCount = e.FailedPasswordAnswerAttemptCount;
                if (failureCount == 0
                    || DateTime.Now > e.FailedPasswordAnswerAttemptWindowStart.AddMinutes(passwordAttemptWindow))
                {
                    e.FailedPasswordAnswerAttemptCount = 1;
                    e.FailedPasswordAnswerAttemptWindowStart = DateTime.Now;
                }
            }
            failureCount++;
            if (failureCount >= maxInvalidPasswordAttempts)
            {
                e.IsLockedOut = true;
                e.LastLockedOutDate = DateTime.Now;
            }
            else
            {
                if (failureType == FailureType.Password)
                    e.FailedPasswordAttemptCount = failureCount;
                else if (failureType == FailureType.PasswordAnswer)
                    e.FailedPasswordAnswerAttemptCount = failureCount;
            }
            objScope.Transaction.Commit();
        }
 public virtual Exception OnError <T>(HystrixCommand <T> commandInstance, FailureType failureType, Exception e)
 {
     // pass-thru by default
     return(e);
 }
Ejemplo n.º 44
0
        /// <summary>
        /// Determines the starting part in the failure.
        /// </summary>
        private void PrepareStartingPart()
        {
            Log.Info("PrepareStartingPart");
            // Find engines
            bool b = !experimentalPartFailure;

            List <Part>         activeEngineParts  = activeVessel.GetActiveParts().Where(o => KLFUtils.PartIsActiveEngine(o, b)).ToList();
            List <Part>         radialDecouplers   = activeVessel.Parts.Where(o => KLFUtils.PartIsRadialDecoupler(o, b)).ToList();
            List <Part>         controlSurfaces    = activeVessel.Parts.Where(o => KLFUtils.PartIsControlSurface(o, b)).ToList();
            List <CompoundPart> strutsAndFuelLines = activeVessel.Parts.OfType <CompoundPart>().Where(o => KLFUtils.PartIsStrutOrFuelLine(o, b)).ToList();

            int cnt = activeEngineParts.Count + radialDecouplers.Count + controlSurfaces.Count + strutsAndFuelLines.Count;

            // If there are no active engines or radial decouplers, skip this attempt.
            if (cnt == 0)
            {
                return;
            }

            // Determine the starting part.
            int startingPartIndex = KLFUtils.RNG.Next(0, cnt);

            Log.Info("activeEngineParts.Count: " + activeEngineParts.Count.ToString() + "    radialDecouplers.Count: " + radialDecouplers.Count.ToString() +
                     "   controlSurfaces.Count: " + controlSurfaces.Count.ToString() + "   strutsAndFuelLines.Count: " + strutsAndFuelLines.Count);
            Log.Info("startingPartIndex: " + startingPartIndex.ToString());

            // for debugging only: startingPartIndex = activeEngineParts.Count;
            int offset = 0;

            if (startingPartIndex < activeEngineParts.Count)
            {
                startingPart = activeEngineParts[startingPartIndex];
                failureType  = FailureType.engine;

                // Get the engine module for the part.
                foreach (ModuleEngines engineModule in startingPart.Modules.OfType <ModuleEngines>().ToList())
                {
                    if (engineModule.enabled && engineModule.currentThrottle > 0)
                    {
                        startingPartEngineModule = engineModule;
                    }
                }
            }
            offset += activeEngineParts.Count;
            if (startingPartIndex >= offset && startingPartIndex < offset + radialDecouplers.Count)
            {
                startingPart = radialDecouplers[startingPartIndex - offset];

                failureType       = FailureType.radialDecoupler;
                decouplerForceCnt = 0;
            }
            offset += radialDecouplers.Count;
            if (startingPartIndex >= offset && startingPartIndex < offset + controlSurfaces.Count)
            {
                startingPart = controlSurfaces[startingPartIndex - offset];

                failureType       = FailureType.controlSurface;
                decouplerForceCnt = 0;
            }
            offset += controlSurfaces.Count;
            if (startingPartIndex >= offset && startingPartIndex < offset + strutsAndFuelLines.Count)
            {
                startingPart = strutsAndFuelLines[startingPartIndex - offset];

                failureType       = FailureType.strutOrFuelLine;
                decouplerForceCnt = 0;
            }



#if false
            if (startingPartIndex >= activeEngineParts.Count)
            {
                startingPart = radialDecouplers[startingPartIndex - activeEngineParts.Count];

                failureType       = FailureType.radialDecoupler;
                decouplerForceCnt = 0;
            }
            else
            {
                startingPart = activeEngineParts[startingPartIndex];
                failureType  = FailureType.engine;

                // Get the engine module for the part.
                startingPartEngineModule = startingPart.Modules.OfType <ModuleEngines>().Single();
            }
#endif
            // Setup tick information for the part explosion loop.
            ticksBetweenPartFailures = (int)(KLFUtils.GameTicksPerSecond * KLFSettings.Instance.DelayBetweenPartFailures);
            if (ticksBetweenPartFailures == 0)
            {
                ticksBetweenPartFailures = (int)(KLFUtils.GameTicksPerSecond / 20f + 1f);
            }
            ticksSinceFailureStart = 0;
            thrustOverload         = 0;
            underThrustStart       = 100f;
            underThrustEnd         = 100f;
            scienceAfterFailure    = CalcScienceReward(activeVesselCost, activeVessel, startingPart);
            preFailureWarningTime  = KLFSettings.Instance.PreFailureWarningTime;
            if (KLFSettings.Instance.TimeRandomness > 0)
            {
                float f = UnityEngine.Random.Range(0, KLFSettings.Instance.TimeRandomness) - KLFSettings.Instance.TimeRandomness / 2f;
                preFailureWarningTime += f;
            }
        }
Ejemplo n.º 45
0
        private async Task <T> GetFallbackOrThrowException(EventType eventType, FailureType failureType, string message, Exception ex)
        {
            try
            {
                if (IsUnrecoverable(ex))
                {
                    Logger.LogError("Unrecoverable Error for Command so will throw RuntimeException and not apply fallback. ", ex);
                    // record the _executionResult
                    _executionResult.AddEvent(eventType);

                    /* executionHook for all errors */
                    throw new CommandRuntimeException(failureType, CommandName, GetLogMessagePrefix() + " " + message + " and encountered unrecoverable error.", ex, null);
                }

                ex = _executionHook.OnError(this, failureType, ex);

                _executionResult.AddEvent(eventType);

                if ((_flags & ServiceCommandOptions.HasFallBack) != ServiceCommandOptions.HasFallBack || Properties.FallbackEnabled.Value == false)
                {
                    throw new CommandRuntimeException(failureType, CommandName, GetLogMessagePrefix() + " " + message + " and fallback disabled.", ex, null);
                }

                if (FallBackSemaphore.TryAcquire()) // fallback semaphore
                {
                    try
                    {
                        _executionHook.OnFallbackStart(this);
                        var fallback = await GetFallback();

                        try
                        {
                            _executionHook.OnFallbackSuccess(this);
                        }
                        catch (Exception hookEx)
                        {
                            Logger.LogWarning("Error calling CommandExecutionHook.onFallbackSuccess", hookEx);
                        }
                        Metrics.MarkFallbackSuccess();
                        _executionResult.AddEvent(EventType.FALLBACK_SUCCESS);
                        return(fallback);
                    }
                    catch (Exception ex2)
                    {
                        try
                        {
                            ex2 = _executionHook.OnFallbackError(this, ex2);
                        }
                        catch (Exception hookEx)
                        {
                            Logger.LogWarning("Error calling CommandExecutionHook.onFallbackError", hookEx);
                        }

                        var fe = ex2 is AggregateException ? ((AggregateException)ex2).InnerException : ex2;
                        if (fe is NotImplementedException)
                        {
                            Logger.LogDebug("No fallback for Command. ", fe); // debug only since we're throwing the exception and someone higher will do something with it
                            throw new CommandRuntimeException(failureType, CommandName, GetLogMessagePrefix() + " and no fallback available.", ex, fe);
                        }
                        else
                        {
                            Metrics.MarkFallbackFailure();
                            _executionResult.AddEvent(EventType.FALLBACK_FAILURE);
                            throw new CommandRuntimeException(failureType, CommandName, GetLogMessagePrefix() + " and fallback failed.", ex, fe);
                        }
                    }
                    finally
                    {
                        FallBackSemaphore.Release();
                    }
                }
                else
                {
                    Metrics.MarkFallbackRejection();
                    _executionResult.AddEvent(EventType.FALLBACK_REJECTION);
                    Logger.LogDebug("Command Fallback Rejection."); // debug only since we're throwing the exception and someone higher will do something with it
                    // if we couldn't acquire a permit, we "fail fast" by throwing an exception
                    throw new CommandRuntimeException(FailureType.REJECTED_SEMAPHORE_FALLBACK, CommandName, GetLogMessagePrefix() + "fallback execution rejected.", null, null);
                }
            }
            catch
            {
                // count that we are throwing an exception
                Metrics.MarkExceptionThrown();
                throw;
            }
        }
Ejemplo n.º 46
0
 void Fail(TestStatus status, FailureType failureType, Exception ex)
 {
     Status = status;
     var fixtureFailure = ex as FixtureException;
     if(fixtureFailure != null)
         for(var i = 0; i != fixtureFailure.Count; ++i)
             log.Failure(new ConeTestFailure(test.TestName, fixtureFailure[i], failureType));
     else
         log.Failure(new ConeTestFailure(test.TestName, ex, failureType));
 }
Ejemplo n.º 47
0
 /// <nodoc />
 public FileDownloadFailure(string toolName, string url, string targetLocation, FailureType type, Exception exception = null)
 {
     ToolName       = toolName;
     Url            = url;
     TargetLocation = targetLocation;
     FailureType    = type;
     Exception      = exception;
 }
Ejemplo n.º 48
0
 public OmniCoreRepositoryException(FailureType failureType, string message = null, Exception inner = null) : base(failureType, message, inner)
 {
 }
Ejemplo n.º 49
0
 /// <nodoc />
 public FileDownloadFailure(string toolName, string url, string targetLocation, FailureType type, Failure failure)
     : base(failure)
 {
     ToolName       = toolName;
     Url            = url;
     TargetLocation = targetLocation;
     FailureType    = type;
 }
Ejemplo n.º 50
0
 protected OmniCoreException(FailureType failureType, string message = null, Exception inner = null) : base(message, inner)
 {
     FailureType = failureType;
 }
 public override Exception OnError(IHystrixInvokable commandInstance, FailureType failureType, Exception e)
 {
     CommandEmissions.Add(Notification.CreateOnError <object>(e));
     RecordHookCall(ExecutionSequence, "onError");
     return(base.OnError(commandInstance, failureType, e));
 }
 public override Exception OnError <T>(ServiceCommand <T> commandInstance, FailureType failureType, Exception e)
 {
     Write(commandInstance, e);
     return(base.OnError <T>(commandInstance, failureType, e));
 }
        private void UpdateFailureCount(DataRow membershipRecord, FailureType failureType, DataSet ds)
        {
            DataRow dr = membershipRecord;
            DateTime windowStart = new DateTime();
            int failureCount = 0;
            try
            {
                switch (failureType)
                {
                    case FailureType.Password:
                        failureCount = int.Parse(dr["FailedPasswordAttemptCount"].ToString());
                        windowStart = DateTime.Parse(dr["FailedPasswordAttemptWindowStart"].ToString());
                        break;
                    case FailureType.PasswordAnswer:
                        failureCount = int.Parse(dr["FailedPasswordAnswerAttemptCount"].ToString());
                        windowStart = DateTime.Parse(dr["FailedPasswordAnswerAttemptWindowStart"].ToString());
                        break;
                }

                DateTime windowEnd = windowStart.AddMinutes(PasswordAttemptWindow);

                if (failureCount == 0 || DateTime.Now > windowEnd)
                {
                    // First password failure or outside of PasswordAttemptWindow.
                    // Start a new password failure count from 1 and a new window
                    //   starting now.

                    if (failureType == FailureType.Password)
                    {
                        dr["PasswordAttemptCount"] = 1;
                        dr["PasswordAttemptWindowStart"] = DateTime.Now;
                    }
                    else if (failureType == FailureType.PasswordAnswer)
                    {
                        dr["PasswordAnswerAttemptCount"] = 1;
                        dr["PasswordAnswerAttemptWindowStart"] = DateTime.Now;
                    }
                }
                else
                {
                    if (failureCount++ >= this.MaxInvalidPasswordAttempts)
                    {
                        // Password attempts have exceeded the failure threshold.
                        //   Lock out the user.
                        dr["IsLockedOut"] = true;
                    }
                    else
                    {
                        // Password attempts have not exceeded the failure
                        //   threshold. Update the failure counts. Leave the
                        //   window the same.
                        if (failureType == FailureType.Password)
                            dr["PasswordAttemptCount"] = failureCount;

                        else if (failureType == FailureType.PasswordAnswer)
                            dr["PasswordAnswerAttemptCount"] = failureCount;
                    }
                }
                //ds.Tables["Membership"].LoadDataRow(membershipRecord.ItemArray, false);
                this.SaveXml(ds);
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 54
0
 public Failure(Device failedDevice, DateTime failureDate, FailureType failureType)
 {
     Device = failedDevice;
     Date   = failureDate;
     Type   = failureType;
 }
Ejemplo n.º 55
0
		public ConeTestFailure(ITestName testName, Exception error, FailureType failureType) : this(testName, error, failureType, ShouldIncludeFrame)
		{ }