public void Should_throw_when_policyname_is_empty() { // Arrange const string emptyPolicyName = ""; var policyResult = PolicyResult.CreateFailureResult(new IgnorePolicy(), "Failure message"); // Act & assert Assert.Throws <ArgumentException>(() => new DelegatePolicyResult(policyResult, emptyPolicyName, null)); }
// create a empty result internal AuthorizationResult() { expression = null; result = PolicyResult.NotHandled; succeededPolicies = new SortedSet <string>(); failedPolicies = new SortedSet <string>(); notHandledPolicies = new SortedSet <string>(); policyResults = new Dictionary <string, PolicyResult>(); }
public DelegatePolicyResult(PolicyResult policyResult, string policyName, Func<PolicyViolationException, ActionResult> violationHandler) : base(policyResult.Message, policyResult.ViolationOccured, policyResult.PolicyType) { if (String.IsNullOrWhiteSpace(policyName)) throw new ArgumentException("policyName"); PolicyName = policyName; ViolationHandler = violationHandler; }
/// <summary> /// Starts polling for a <paramref name="minimumNumberOfItems"/> corresponding to the previously set filtering criteria. /// </summary> /// <param name="minimumNumberOfItems">The minimum amount of logic app runs to retrieve.</param> public async Task <IEnumerable <LogicAppRun> > PollForLogicAppRunsAsync(int minimumNumberOfItems) { Guard.NotLessThanOrEqualTo(minimumNumberOfItems, 0, nameof(minimumNumberOfItems)); string amount = minimumNumberOfItems == 1 ? "any" : minimumNumberOfItems.ToString(); RetryPolicy <IEnumerable <LogicAppRun> > retryPolicy = Policy.HandleResult <IEnumerable <LogicAppRun> >(currentLogicAppRuns => { int count = currentLogicAppRuns.Count(); bool isStillPending = count < minimumNumberOfItems; _logger.LogTrace("Polling for {Amount} log app runs, whilst got now {Current} ", amount, count); return(isStillPending); }).Or <Exception>(ex => { _logger.LogError(ex, "Polling for logic app runs was faulted: {Message}", ex.Message); return(true); }) .WaitAndRetryForeverAsync(index => { _logger.LogTrace("Could not retrieve logic app runs in time, wait 1s and try again..."); return(_retryInterval); }); PolicyResult <IEnumerable <LogicAppRun> > result = await Policy.TimeoutAsync(_timeout) .WrapAsync(retryPolicy) .ExecuteAndCaptureAsync(GetLogicAppRunsAsync); if (result.Outcome == OutcomeType.Failure) { if (result.FinalException is null || result.FinalException.GetType() == typeof(TimeoutRejectedException)) { string correlation = _hasCorrelationId ? $"{Environment.NewLine} with correlation property equal '{_correlationId}'" : String.Empty; string trackedProperty = _trackingProperties.Count > 0 ? $" {Environment.NewLine} with tracked properties {{{String.Join(", ", _trackingProperties.Select(prop => $"[{prop.Key}] = {prop.Value}"))}}}" : String.Empty; throw new TimeoutException( $"Could not in the given timeout span ({_timeout:g}) retrieve {amount} logic app runs " + $"{Environment.NewLine} with StartTime >= {_startTime.UtcDateTime:O}" + correlation + trackedProperty); } throw result.FinalException; } _logger.LogTrace("Polling finished successful with {Count} logic app runs", result.Result.Count()); return(result.Result); }
internal AuthorizationResult(IPolicyExpressionRootCombine expression) { this.expression = expression; this.result = expression.Result; succeededPolicies = new SortedSet <string>(); failedPolicies = new SortedSet <string>(); notHandledPolicies = new SortedSet <string>(); policyResults = new Dictionary <string, PolicyResult>(); PolicyResult result; foreach (IPolicyOnlyExpression exp in expression) { if (policyResults.TryGetValue(exp.Policy, out result)) { switch (result) { case PolicyResult.Success: case PolicyResult.Failed: // keep break; case PolicyResult.NotHandled: default: // overwrite if (exp.Result != PolicyResult.NotHandled) { policyResults[exp.Policy] = exp.Result; } break; } } else { policyResults.Add(exp.Policy, exp.Result); } } foreach (var pair in policyResults) { switch (pair.Value) { case PolicyResult.Success: succeededPolicies.Add(pair.Key); break; case PolicyResult.Failed: failedPolicies.Add(pair.Key); break; case PolicyResult.NotHandled: default: notHandledPolicies.Add(pair.Key); break; } } }
/// <summary> /// 无限重试,直至func执行成功 /// </summary> /// <param name="func">实际的业务逻辑</param> /// <param name="retryCallback">每次重试之前的回调</param> /// <returns></returns> public static PolicyResult <T> RetryForver <T>(Func <T> func, Action <Exception> retryCallback = null) { PolicyResult <T> result = Policy.Handle <Exception>().RetryForever(exception => { //重试之前的回调 retryCallback?.Invoke(exception); }).ExecuteAndCapture(func); return(result); }
/// <summary> /// 重试次数和sleepDurations的个数相同 总的执行次数为重试次数+1 /// </summary> /// <param name="sleepDurations">每次重试之前的间隔 不能为null</param> /// <param name="func">要执行的业务逻辑func</param> /// <param name="retryCallback"></param> /// <returns>The result of executing the policy. Will be default(TResult) is the policy failed</returns> public static PolicyResult <T> RetryAndWaitImplicitly <T>(Func <T> func, IEnumerable <TimeSpan> sleepDurations, Action <Exception, TimeSpan, int> retryCallback = null) { PolicyResult <T> result = Policy.Handle <Exception>().WaitAndRetry(sleepDurations, (exception, span, count, context) => { //在每次重试之前执行,span表示当前重试的时间间隔 count表示重试次数,从1开始计数 retryCallback?.Invoke(exception, span, count); }).ExecuteAndCapture(func); return(result); }
/// <summary> /// 无限重试,直至action执行成功 /// </summary> /// <param name="action">实际的业务逻辑</param> /// <param name="retryCallback">每次重试之前的回调</param> /// <returns></returns> public static PolicyResult RetryForver(Action action, Action <Exception> retryCallback = null) { PolicyResult result = Policy.Handle <Exception>().RetryForever(exception => { //重试之前的回调 retryCallback?.Invoke(exception); }).ExecuteAndCapture(action); return(result); }
private async Task <bool> SendAsync(string idempotencyKey, List <EventLog> eventLogList) { _loggerService.StartMethod(); try { var request = new V1EventLogRequest() { IdempotencyKey = idempotencyKey, Platform = _essentialsService.Platform, AppPackageName = _essentialsService.AppPackageName, EventLogs = eventLogList, }; // Create device verification payload PolicyResult <string> policyResult = await Policy .HandleResult <string>(result => _deviceVerifier.IsErrorPayload(result)) .WaitAndRetryAsync(3, retryAttempt => { double delay = Math.Pow(2, retryAttempt + 1); _loggerService.Warning($"Payload creation failed. retryAttempt:{retryAttempt} delay:{delay}sec"); return(TimeSpan.FromSeconds(delay)); }) .ExecuteAndCaptureAsync(() => _deviceVerifier.VerifyAsync(request)); if (policyResult.Outcome == OutcomeType.Failure) { _loggerService.Error("Payload creation failed all."); return(false); } _loggerService.Info("Payload creation successful."); request.DeviceVerificationPayload = policyResult.Result; ApiResponse <string> response = await _httpDataService.PutEventLog(request); _loggerService.Info($"PutEventLog() StatusCode:{response.StatusCode}"); if (response.StatusCode == (int)HttpStatusCode.Created) { _loggerService.Info("Send event log succeeded"); return(true); } } catch (Exception ex) { _loggerService.Exception("Exception occurred, SendAsync", ex); } finally { _loggerService.EndMethod(); } _loggerService.Error("Send event log failure"); return(false); }
public async Task <PolicyResult> GetPolicyAsync(HttpContext context) { PolicyResult result = await _cache.GetAsync( context.User.Identity.Name, _options.Caching.LocalUserPermissionExpiration, () => _inner.GetPolicyAsync(context), _logger ); return(result); }
public override PolicyResult Enforce(TSecurityContext securityContext) { if (securityContext != null) { WasCalledWithCustomContext = true; } CustomContext = securityContext; return(PolicyResult.CreateSuccessResult(this)); }
public DelegatePolicyResult(PolicyResult policyResult, string policyName, Func <PolicyViolationException, ActionResult> violationHandler) : base(policyResult.Message, policyResult.ViolationOccured, policyResult.PolicyType) { if (string.IsNullOrWhiteSpace(policyName)) { throw new ArgumentException("policyName"); } PolicyName = policyName; ViolationHandler = violationHandler; }
/// <summary> /// 重试多次没有时间间隔,返回true表示最终执行成功 false表示执行失败 /// </summary> /// <param name="retryCount">大于等于0,表示重试的次数,实际最多执行retryCount+1次</param> /// <param name="action">需要执行的业务逻辑</param> /// <param name="retryCallback">每次重试前的回调</param> /// <returns></returns> public static PolicyResult Retry(Action action, int retryCount = 1, Action <Exception, int> retryCallback = null) { PolicyResult result = Policy.Handle <Exception>().Retry(retryCount, ((exception, count) => { /* * 如果action没有抛出异常,此回调不执行,否则执行 count从1开始,在调用action之前执行 exception表示上次的异常 */ retryCallback?.Invoke(exception, count); })).ExecuteAndCapture(action); return(result); }
public void ShouldSucceedWhenNoCreateDatabaseScriptExists() { // Setup DirectoryInfo directoryInfo = DirectoryStructureHelper.CreateValidDatabaseDirStructure("ShouldSucceedWhenNoCreateDatabaseScriptExists"); IFileStructurePolicy policy = new MustContainCreateDatabaseSqlFilePolicy(); PolicyResult result = policy.Check(directoryInfo); // Assert Assert.That(result.Success, Is.True); }
public PolicyResult Enforce(ISecurityContext context) { bool hasPermission; using (var dbContext = new AppDbContext()) { hasPermission = dbContext.Users.HasPermission(Permissions); } return(hasPermission ? PolicyResult.CreateSuccessResult(this) : PolicyResult.CreateFailureResult(this, (Permissions).ToString())); }
public void DirectoryStructurePolicyCheckMustSucceedWithValidStructure() { // Setup DirectoryInfo databaseScriptsRoot = DirectoryStructureHelper.CreateValidDatabaseDirStructure("DirectoryStructureMustBeCorrectTest"); DirectoryStructurePolicy directoryStructurePolicy = new DirectoryStructurePolicy(); PolicyResult result = directoryStructurePolicy.Check(databaseScriptsRoot); Assert.IsTrue(result.Success, string.Join(Environment.NewLine, result.Messages.ToArray())); Assert.IsEmpty(result.Messages); }
public async Task <PolicyResult <TOutput> > ExecuteWithTimeoutAsync <TOutput>(Func <CancellationToken, TOutput> func, int timeout, CancellationToken relatedToken) { CancellationEnforcer <TOutput> cancellationEnforcer = new CancellationEnforcer <TOutput>(); // need a little bit of extra time to allow the globalTimer to execute first AsyncTimeoutPolicy timeoutPolicy = Policy.TimeoutAsync(timeout + 1, TimeoutStrategy.Optimistic); PolicyResult <TOutput> policyResult = await timeoutPolicy.ExecuteAndCaptureAsync( async ct => await cancellationEnforcer.AskVinnyToKeepWatch(func, ct), relatedToken ); return(policyResult); }
public void Should_be_successful_and_have_no_message() { // Arrange var policy = new DenyAnonymousAccessPolicy(); // Act var result = PolicyResult.CreateSuccessResult(policy); // Assert Assert.That(result.ViolationOccured, Is.False); Assert.That(result.Message, Is.Null); Assert.That(result.PolicyType, Is.EqualTo(policy.GetType())); }
public override PolicyResult Enforce(ISecurityContext context) { var marketId = GetMarketParameter(context); if (!marketId.HasValue || HasAccessToMarket(marketId.Value)) { return(PolicyResult.CreateSuccessResult(this)); } return(PolicyResult.CreateFailureResult(this, string.Format("User '{0}' does not have sufficient permissions to access data for market '{1}'.", SecurityHelper.GetAuthenticatedUser(), GetMarketName(marketId.Value)))); }
public void AtLeastOneDirectoryMustContainSqlFilesFailsOnEmptyDirs() { // Setup DirectoryInfo directoryInfo = DirectoryStructureHelper.CreateValidDatabaseDirStructure("AtLeastOneDirectoryMustContainSqlFilesTest"); IFileStructurePolicy policy = new MustContainSqlFilePolicy(); PolicyResult result = policy.Check(directoryInfo); // Empty directory. Policy should fail. Assert.IsFalse(result.Success); Assert.That(result.Messages.Count, Is.EqualTo(1)); }
static void Main(string[] args) { var logger = new Logger(); var policy = Policy .Handle <TimeoutException>() .WaitAndRetry(Enumerable.Repeat(TimeSpan.FromSeconds(5), 3), (exception, timespan) => { logger.Warn($"{exception} trying again in {timespan}"); }); PolicyResult result = policy.ExecuteAndCapture(() => TransientOperation()); }
/// <summary> /// 重试多次没有时间间隔 返回func执行的结果 /// </summary> /// <param name="retryCount">大于等于0,表示重试的次数,实际最多执行retryCount+1次</param> /// <param name="func">需要执行的业务逻辑</param> /// <param name="retryCallback">每次重试前的回调</param> /// <returns>The result of executing the policy. Will be default(TResult) is the policy failed</returns> public static PolicyResult <T> Retry <T>(Func <T> func, int retryCount = 1, Action <Exception, int> retryCallback = null) { PolicyResult <T> result = Policy.Handle <Exception>().Retry(retryCount, ((exception, count) => { /* * 如果func没有抛出异常,此回调不执行,否则执行 count从1开始,在调用func之前执行 exception表示上次的异常 * */ retryCallback?.Invoke(exception, count); })).ExecuteAndCapture(func); return(result); }
public void Should_have_PolicyResult_PolicyType_and_Message_set() { // Arrange var policy = new DenyAnonymousAccessPolicy(); var policyResult = PolicyResult.CreateFailureResult(policy, "Anonymous access denied"); // Act var exception = new PolicyViolationException(policyResult); // Assert Assert.That(exception.PolicyResult, Is.EqualTo(policyResult)); Assert.That(exception.PolicyType, Is.EqualTo(typeof(DenyAnonymousAccessPolicy))); Assert.That(exception.Message, Is.EqualTo("Anonymous access denied")); }
public void ShouldSucceedWhenOnlyOneCreateDatabaseScriptExists() { // Setup DirectoryInfo directoryInfo = DirectoryStructureHelper.CreateValidDatabaseDirStructure("ShouldSucceedWhenOnlyOneCreateDatabaseScriptExists"); IFileStructurePolicy policy = new MustContainCreateDatabaseSqlFilePolicy(); DirectoryStructureHelper.CreateEmptyFile(Path.Combine(directoryInfo.GetDirectories()[1].FullName, "CreateDatabase.sql")); PolicyResult result = policy.Check(directoryInfo); // Assert Assert.That(result.Success, Is.True); }
// public async Task<Boolean> IsInRoleAsync(ClaimsPrincipal user, String role) { // PolicyResult policy = await EvaluateAsync(user); // return policy.Roles.Contains(role); // } // public async Task<Boolean> HasPermissionAsync(ClaimsPrincipal user, String permission) { // PolicyResult policy = await EvaluateAsync(user); // return policy.Permissions.Contains(permission); // } public async Task <PolicyResult> EvaluateAsync(Policy policy, ClaimsPrincipal user) { if (policy.Hash.IsMissing()) { policy.CalculateHash(); } if (policy.LastPolicyChangeDate == DateTime.MinValue) { policy.LastPolicyChangeDate = DateTime.Now; } PolicyResult result = await policy.EvaluateAsync(user); return(result); }
public PolicyResult Enforce(FluentSecurity.ISecurityContext context) { PolicyResult result = PolicyResult.CreateFailureResult(this, "Access denied!"); if (context.CurrentUserRoles() != null) { if (context.CurrentUserRoles().Contains("Admin")) { result = PolicyResult.CreateSuccessResult(this); } } return(result); }
public void Should_be_successful_when_delegate_returns_success() { // Arrange Func <DelegateSecurityContext, PolicyResult> successDelegate = c => PolicyResult.CreateSuccessResult(c.Policy); var policy = new DelegatePolicy(ValidPolicyName, successDelegate, ValidViolationHandlerDelegate); var context = TestDataFactory.CreateSecurityContext(true); // Act var result = policy.Enforce(context); // Assert Assert.That(result, Is.TypeOf <DelegatePolicyResult>()); Assert.That(result.ViolationOccured, Is.False); }
public void Should_be_unsuccessful_and_have_a_message() { // Arrange var message = "Failure"; var policy = new DenyAnonymousAccessPolicy(); // Act var result = PolicyResult.CreateFailureResult(policy, message); // Assert Assert.That(result.ViolationOccured, Is.True); Assert.That(result.Message, Is.EqualTo(message)); Assert.That(result.PolicyType, Is.EqualTo(policy.GetType())); }
private static BlockWithTransactions GetBlockWithTransactions(Policy pollyRetryPolicy, Web3 web3, long blockNumber) { PolicyResult <BlockWithTransactions> capture = pollyRetryPolicy.ExecuteAndCapture(() => { BlockWithTransactions rpcBlock = web3.Eth.Blocks.GetBlockWithTransactionsByNumber .SendRequestAsync(new HexBigInteger(blockNumber)).Result; return(rpcBlock); }); BlockWithTransactions ethBlock = capture.Result; return(ethBlock); }
public void Should_not_be_successful_when_delegate_returns_failure() { // Arrange Func <DelegateSecurityContext, PolicyResult> failureDelegate = c => PolicyResult.CreateFailureResult(c.Policy, "Access denied"); var policy = new DelegatePolicy(ValidPolicyName, failureDelegate, ValidViolationHandlerDelegate); var context = TestDataFactory.CreateSecurityContext(true); // Act var result = policy.Enforce(context); // Assert Assert.That(result, Is.TypeOf <DelegatePolicyResult>()); Assert.That(result.ViolationOccured, Is.True); Assert.That(result.Message, Is.EqualTo("Access denied")); }
public void Should_throw_when_no_violation_handler_has_been_set_and_no_violation_handler_match_name() { // Arrange var violationHandlers = Enumerable.Empty <IPolicyViolationHandler>(); var failureResult = PolicyResult.CreateFailureResult(new IgnorePolicy(), "Access denied"); var policy = new DelegatePolicy("Test", c => failureResult); var delegatePolicyResult = new DelegatePolicyResult(failureResult, policy.Name, policy.ViolationHandler); var exception = new PolicyViolationException(delegatePolicyResult); var handler = new DelegatePolicyViolationHandler(violationHandlers); // Act & assert var caughtException = Assert.Throws <PolicyViolationException>(() => handler.Handle(exception)); Assert.That(caughtException, Is.EqualTo(exception)); }
public Task SetBlockPolicy(PolicyResult result) { return Task.Factory.StartNew(() => _blockPolicy = result); }
public Task SetSystemFeedsPolicy(PolicyResult result) { throw new NotImplementedException(); }
public Task SetUpdatePolicy(PolicyResult result) { throw new NotImplementedException(); }
public Task SetSetStatePolicy(PolicyResult result) { return SetStatePolicy.ContinueWith(t => ModifyPolicy(t, result, PolicyType.ChangeState)).ContinueWith( t => { t.RethrowWhenFaulted(); Messenger.Default.Send(new PoliciesUpdatedMessage()); }); }
public static PolicyViolationException CreatePolicyViolationException(PolicyResult policyResult, ISecurityContext securityContext = null) { return new PolicyViolationException(policyResult, securityContext ?? CreateSecurityContext(false)); }
private void ModifyPolicy(Task<PolicyResult> currentPolicyTask, PolicyResult newPolicy, PolicyType policyToSet) { if (currentPolicyTask.IsFaulted) throw new Exception(); PolicyResult currentPolicy = currentPolicyTask.Result; IIdentity currentUser = UserService.GetCurrentUser(); //get the current install policy if (currentPolicy == PolicyResult.Everyone) { if (newPolicy == PolicyResult.CurrentUser) { //remove everyone CoApp.RemovePrincipalFromPolicy(policyToSet, WORLDSID.Value); //add user CoApp.AddPrincipalToPolicy(policyToSet, currentUser.Name); } else if (newPolicy == PolicyResult.Everyone) { //do nothing } else if (newPolicy == PolicyResult.Other) { //remove everyone CoApp.RemovePrincipalFromPolicy(policyToSet, WORLDSID.Value); } } else if (currentPolicy == PolicyResult.CurrentUser) { if (newPolicy == PolicyResult.CurrentUser) { //do nothing } else if (newPolicy == PolicyResult.Everyone) { //remove CurrentUser CoApp.RemovePrincipalFromPolicy(policyToSet, currentUser.Name); //add everyone CoApp.AddPrincipalToPolicy(policyToSet, WORLDSID.Value); } else if (newPolicy == PolicyResult.Other) { //remove CurrentUser CoApp.RemovePrincipalFromPolicy(policyToSet, currentUser.Name); } } else if (currentPolicy == PolicyResult.Other) { if (newPolicy == PolicyResult.CurrentUser) { //add currentuser CoApp.AddPrincipalToPolicy(policyToSet, currentUser.Name); } else if (newPolicy == PolicyResult.Everyone) { //add everyone CoApp.AddPrincipalToPolicy(policyToSet, WORLDSID.Value); } else if (newPolicy == PolicyResult.Other) { //do nothing } } }
public Task SetUpdatePolicy(PolicyResult result) { return Task.Factory.StartNew(() => _updatePolicy = result); }
public Task SetSystemFeedsPolicy(PolicyResult result) { return Task.Factory.StartNew(() => _sysFeedsPolicy = result); }
public Task SetRequirePolicy(PolicyResult result) { return Task.Factory.StartNew(() => _requirePolicy = result); }
public Task SetInstallPolicy(PolicyResult result) { return Task.Factory.StartNew(() => _installPolicy = result); }
public Task SetActivePolicy(PolicyResult result) { return Task.Factory.StartNew(() => _activePolicy = result); }
public Task SetInstallPolicy(PolicyResult policyToSet) { return InstallPolicy.ContinueWith(t => ModifyPolicy(t, policyToSet, PolicyType.InstallPackage)).ContinueWith( t => { t.RethrowWhenFaulted(); Messenger.Default.Send(new PoliciesUpdatedMessage()); } ); }
public Task SetFreezePolicy(PolicyResult result) { return Task.Factory.StartNew(() => _freezePolicy = result); }