static void Main(string[] args) { // create web service proxy // NOTE!!! When updating web reference in Visual Studio, // don't forget to change its base class to Microsoft.Web.Services3.WebServicesClientProtocol then WseSample.Service srv = new WseSample.Service(); // create custom SOAP header and assign it to web service WseSample.BankAccountSettings settings = new WseSample.BankAccountSettings(); settings.PinCode = "1111"; srv.BankAccountSettingsValue = settings; // create custom policy assertion and assign it to proxy // for password we just use reversed username // it's important, because UsernameTokenManager on the service side applies the same logic // when looking for user password UsernameClientAssertion assert = new UsernameClientAssertion("admin", "nimda"); // create policy Policy policy = new Policy(); policy.Assertions.Add(assert); // and set it to web service srv.SetPolicy(policy); // invoke web service method bool valid = srv.CheckAccountStatus("123456"); Debug.WriteLine(valid); }
static void Main(string[] args) { MyMathServiceWse serviceProxy = new MyMathServiceWse(); //UsernameToken token = new UsernameToken("zhang3", "f0f5671b9ec568d03cbe126ce135a8b3d6ce6ab2", PasswordOption.SendPlainText); //serviceProxy.SetClientCredential(token); //X509Certificate2 myServerCert = new X509Certificate2("myServer.pem.cer"); //serviceProxy.SetServiceCredential(new X509SecurityToken(myServerCert)); UsernameForCertificateAssertion assert = new UsernameForCertificateAssertion(); assert.RenewExpiredSecurityContext = true; assert.RequireSignatureConfirmation = false; assert.Protection.DefaultOperation.Request.CustomSignedHeaders.Clear(); assert.Protection.DefaultOperation.Request.EncryptBody = true; assert.Protection.DefaultOperation.Request.SignatureOptions = SignatureOptions.IncludeNone; assert.Protection.DefaultOperation.Response.EncryptBody = false; assert.Protection.DefaultOperation.Response.SignatureOptions = SignatureOptions.IncludeNone; MutualCertificate10Assertion assertion1 = new MutualCertificate10Assertion() { EstablishSecurityContext = false, RenewExpiredSecurityContext = true, RequireSignatureConfirmation = false, MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt, RequireDerivedKeys = false, TtlInSeconds = 300 }; //assertion1.ClientX509TokenProvider = new X509TokenProvider(StoreLocation.CurrentUser, StoreName.My, "CN=myClient,OU=R & D department,O=BJ SOS Software Tech Co.\\, Ltd,L=Beijing,ST=Beijing,C=CN", X509FindType.FindBySubjectDistinguishedName); assertion1.ClientX509TokenProvider = new X509TokenProvider(StoreLocation.CurrentUser, StoreName.My, "1364458997", X509FindType.FindBySerialNumber); assertion1.ServiceX509TokenProvider = new X509TokenProvider(StoreLocation.CurrentUser, StoreName.AddressBook, "1364458964", X509FindType.FindBySerialNumber); Console.Out.WriteLine(111); Console.Out.WriteLine(assertion1.ClientX509TokenProvider.GetToken()); Console.Out.WriteLine(111); Console.Out.WriteLine(assertion1.ServiceX509TokenProvider.GetToken()); Console.Out.WriteLine(222); //protection assertion1.Protection.Request.SignatureOptions = SignatureOptions.IncludeSoapBody; assertion1.Protection.Request.EncryptBody = true; assertion1.Protection.Response.SignatureOptions = SignatureOptions.IncludeSoapBody; assertion1.Protection.Response.EncryptBody = true; assertion1.Protection.Fault.SignatureOptions = SignatureOptions.IncludeSoapBody; assertion1.Protection.Fault.EncryptBody = false; Policy policy = new Policy(); policy.Assertions.Add(assertion1); serviceProxy.SetPolicy(policy); //serviceProxy.RequestSoapContext.Addressing.Action = new Action("http://www.test.me/MyMath/add"); addRequest req = new addRequest(); req.x = 1; req.y = 2; addResponse resp = serviceProxy.add(req); Console.Out.WriteLine("resp = " + resp.@out); }
public Forum(String name, List<User> admins, Policy policy) { if (name == null || name.Length < 1) { Console.Out.WriteLine("Error: u idiot"); } else if (admins == null || admins.Count < 1) { Console.Out.WriteLine("Error: u idiot2"); } else if (policy == null) { Console.Out.WriteLine("Error: u idiot3"); } else { this.name = name; for (int i = 0; i < admins.Count; i++) { this.members.Add(admins.ElementAt(i)); this.admins.Add(i); } subforums = new List<SubForum>(); this.policy = policy; } }
public void Configure(WebServicesClientProtocol proxy) { // set proxy URL string serverUrl = enterpriseServerUrl.Trim(); if (serverUrl.Length == 0) throw new Exception("Enterprise Server URL could not be empty"); int idx = proxy.Url.LastIndexOf("/"); // strip the last slash if any if (serverUrl[serverUrl.Length - 1] == '/') serverUrl = serverUrl.Substring(0, serverUrl.Length - 1); proxy.Url = serverUrl + proxy.Url.Substring(idx); // set timeout proxy.Timeout = 900000; //15 minutes // System.Threading.Timeout.Infinite; if (!String.IsNullOrEmpty(username)) { // create assertion UsernameAssertion assert = new UsernameAssertion(username, password); // apply policy Policy policy = new Policy(); policy.Assertions.Add(assert); proxy.SetPolicy(policy); } }
protected void Page_Init(object sender, EventArgs e) { ctx = new AriClinicContext("AriClinicContext"); // security control, it must be a user logged if (Session["User"] == null) Response.Redirect("Default.aspx"); else { user = CntAriCli.GetUser((Session["User"] as User).UserId, ctx); Process proc = (from p in ctx.Processes where p.Code == "policy" select p).FirstOrDefault<Process>(); per = CntAriCli.GetPermission(user.UserGroup, proc, ctx); btnAccept.Visible = per.Modify; } // if (Request.QueryString["CustomerId"] != null) { patientId = Int32.Parse(Request.QueryString["CustomerId"]); pat = CntAriCli.GetCustomer(patientId, ctx); txtCustomer.Text = pat.FullName; } // if (Request.QueryString["PolicyId"] != null) { policyId = Int32.Parse(Request.QueryString["PolicyId"]); pol = CntAriCli.GetPolicy(policyId, ctx); LoadData(pol); } else { LoadTypeCombo(null); LoadInsuranceCombo(null); } }
private void writePolicy(Policy policy, JsonWriter generator) { generator.WriteObjectStart(); writePropertyValue(generator, JsonDocumentFields.VERSION, policy.Version); if (policy.Id != null) { writePropertyValue(generator, JsonDocumentFields.POLICY_ID, policy.Id); } generator.WritePropertyName(JsonDocumentFields.STATEMENT); generator.WriteArrayStart(); foreach (Statement statement in policy.Statements) { generator.WriteObjectStart(); if (statement.Id != null) { writePropertyValue(generator, JsonDocumentFields.STATEMENT_ID, statement.Id); } writePropertyValue(generator, JsonDocumentFields.STATEMENT_EFFECT, statement.Effect.ToString()); writePrincipals(statement, generator); writeActions(statement, generator); writeResources(statement, generator); writeConditions(statement, generator); generator.WriteObjectEnd(); } generator.WriteArrayEnd(); generator.WriteObjectEnd(); }
public static Policy ReadJsonStringToPolicy(string jsonString) { Policy policy = new Policy(); JsonData jPolicy = JsonMapper.ToObject(jsonString); if (jPolicy[JsonDocumentFields.POLICY_ID] != null && jPolicy[JsonDocumentFields.POLICY_ID].IsString) { policy.Id = (string)jPolicy[JsonDocumentFields.POLICY_ID]; } JsonData jStatements = jPolicy[JsonDocumentFields.STATEMENT] as JsonData; if (jStatements != null && jStatements.IsArray) { foreach (JsonData jStatement in jStatements) { Statement statement = convertStatement(jStatement); if (statement != null) { policy.Statements.Add(statement); } } } return policy; }
public void Executing_the_asynchronous_policies_using_the_synchronous_execute_should_throw_an_invalid_operation_exception(Policy asyncPolicy, string description) { Action action = () => asyncPolicy.Execute(() => { }); action.ShouldThrow<InvalidOperationException>() .WithMessage("Please use the synchronous Retry, RetryForever, WaitAndRetry or CircuitBreaker methods when calling the synchronous Execute method."); }
public static void Enqueue(WaitCallback callback, Policy policy) { switch(policy) { case Policy.Immediate: logger.Info("Immediately running callback {0}", callback.Method.Name); ThreadPool.QueueUserWorkItem(new WaitCallback(callback)); break; case Policy.Queued: lock (queue) { if (cooledDown) { logger.Info("Immediately putting callback {0}", callback.Method.Name); ThreadPool.QueueUserWorkItem( new WaitCallback(callback)); } else { logger.Debug("Queuing callback {0} for later execution", callback.Method.Name); queue.Add(callback); } } break; } }
public TextUndoTransaction(TextUndoHistory textUndoHistory, ITextUndoTransaction parent) { _textUndoHistory = textUndoHistory; _state = UndoTransactionState.Open; _parent = parent; MergePolicy = new Policy(); }
public PolicyDomainModel(Policy policyEntity) { Id = policyEntity.Id; Number = policyEntity.Number; SerialNumber = policyEntity.SerialNumber; DeviceName = policyEntity.DeviceName; }
public void AddAssertion(PolicyAssertion assertion) { if (_securityPolicy == null) _securityPolicy = new Policy(); _securityPolicy.Assertions.Add(assertion); }
public AsyncExists(AsyncCluster cluster, Policy policy, Key key, ExistsListener listener) : base(cluster) { this.policy = policy; this.listener = listener; this.key = key; this.partition = new Partition(key); }
/// <summary> /// 对某个WS进行初始化 /// </summary> /// <param name="ws"></param> /// <param name="username"></param> /// <param name="password"></param> public static void Init(WebServicesClientProtocol ws, string username, string password) { AppContext.UserName = username; AppContext.Password = password; Policy policy = new Policy(); policy.Assertions.Add(new MyAssertion()); ws.SetPolicy(policy); }
public bool ExsistingPolicy(Policy toCheck) { var currentList = GetAll(); foreach (var c in currentList) { if (c.Title == toCheck.Title) return true; } return false; }
public void Delete(Policy delPolicy) { var currentList = GetAll(); currentList.RemoveAll(c => c.Title == delPolicy.Title); File.Delete(_filepath); using (var writer = File.CreateText(_filepath)) { foreach (var c in currentList) { writer.WriteLine("{0}^{1}^{2}^{3}", c.Id, c.Category, c.Title, c.Content); } } }
public WSCommerceIntegrationServiceImplService GetDeferredProxy() { var proxy = new WSCommerceIntegrationServiceImplService(); proxy.Url = "https://tbk.orangepeople.cl/WSWebpayTransaction/cxf/WSCommerceIntegrationService"; Policy policy = new Policy(); CustomPolicyAssertion customPolicy = new CustomPolicyAssertion(this.IssuerCertificateName, this.TransbankCertificateName); policy.Assertions.Add(customPolicy); proxy.SetPolicy(policy); proxy.Timeout = 60000; proxy.UseDefaultCredentials = false; return proxy; }
/// <summary> /// 向缓存中添加一项。 /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="policy">缓存使用的策略(一般是过期策略)</param> /// <param name="region"></param> /// <returns></returns> public bool Add(string key, object value, Policy policy, string region = null) { if (value == null) return false; ChangeChecker checker = null; if (policy != null) { checker = policy.Checker; } return this.AddCore(region, key, new StoredValue() { Value = value, Checker = checker }); }
public XmlDocument RunHardCodePolicy(XmlDocument request) { //load request into typed document TypedXmlDocument txd = new TypedXmlDocument("AdaptivIntegration.BizTalkSample.SampleSchema", request); //load BRE policy from the BTS Rules Engine DB Policy policy = new Policy("AdaptivIntegration.BizTalkSample.Policy"); //Execute the policy policy.Execute(txd); //load up modified document as response XmlDocument response = new XmlDocument(); response.LoadXml(txd.Document.OuterXml); return response; }
public bool Persist(Policy entity) { bool isPeristed = false; try { using (ElearningEntities e = new ElearningEntities()) { e.Policies.Add(entity); e.SaveChanges(); isPeristed = true; } } catch { return isPeristed; } return isPeristed; }
public Policy ToPolicy() { var policy = new Policy {ReportOnlyMode = ReportOnly, ReportUri = ReportUri}; policy.AddDirective(AllowedSources.AsDirective("default-src")); policy.AddDirective(AllowedFontSources.AsDirective("font-src")); policy.AddDirective(AllowedFrameAncestors.AsDirective("frame-ancestors")); policy.AddDirective(AllowedFrameSources.AsDirective("frame-src")); policy.AddDirective(AllowedImageSources.AsDirective("img-src")); policy.AddDirective(AllowedMediaSources.AsDirective("media-src")); policy.AddDirective(AllowedObjectSources.AsDirective("object-src")); policy.AddDirective(AllowedStyleSources.AsDirective("style-src")); policy.AddDirective(AllowedConnectSources.AsAliasedDirective("connect-src", "xhr-src")); policy.AddDirective(AllowedScriptSources.AsDirective("script-src")); return policy; }
public void TestInsertDepartment() { Department d = new Department() { DepartmentID = 1, DepartmentName = "IS", Description = "Information Technology" }; using (DepartmentDAOImpl daoImpl = new DepartmentDAOImpl()) { bool isPer = daoImpl.Persist(d); Assert.IsTrue(isPer); } Policy policy = new Policy() { PolicyID = 1, Version = 1, DepartmentID = d.DepartmentID, PolicyName = "MoonLight", Description = "The Policy about having business outside PetroSA", DocumentBlob = "www/intranet/petrosa/policies/veri", }; using (PolicyDAOImpl daoImpl = new PolicyDAOImpl()) { bool isPer = daoImpl.Persist(policy); Assert.IsTrue(isPer); } }
public bool Merge(Policy entity) { bool isMerge = false; try { using (ElearningEntities e = new ElearningEntities()) { Policy p = e.Policies.First(i => i.PolicyID == entity.PolicyID); p.PolicyName = entity.PolicyName; e.SaveChanges(); isMerge = true; } } catch { return isMerge; } return isMerge; }
public void TestInsertPosition() { Policy policy = new Policy() { PolicyID = 2, Version = 1, PolicyName = "Time", Description = "The Policy about PetroSA's Time schedule", DocumentBlob = "www/intranet/petrosa/policies/Time", }; using (PolicyDAOImpl daoImpl = new PolicyDAOImpl()) { bool isPer = daoImpl.Persist(policy); Assert.IsTrue(isPer); } Position pos = new Position() { PositionID = 1, PolicyID = policy.PolicyID, Version = policy.Version, PositionName = "Finance Services Manager", Description = "Takes care of Money", }; using (PositionDAOImpl daoImpl = new PositionDAOImpl()) { bool isPer = daoImpl.Persist(pos); Assert.IsTrue(isPer); } }
public List<Policy> GetAll() { var reader = File.ReadAllLines(_filepath); var list = new List<Policy>(); for (int i = 0; i < reader.Length; i++) { var columns = reader[i].Split('^'); var policy = new Policy(); policy.Id = Int32.Parse(columns[0]); policy.Category = columns[1]; policy.Title = columns[2]; policy.Content = columns[3]; list.Add(policy); } return list; }
public bool Remove(Policy entity) { bool isRemoved = false; try { using (ElearningEntities e = new ElearningEntities()) { Policy p = e.Policies.First(i => i.PolicyID == entity.PolicyID); e.Policies.Remove(p); e.SaveChanges(); isRemoved = true; } } catch { return isRemoved; } return isRemoved; }
public WSWebpayServiceImplService GetNormalProxy() { try { var proxy = new WSWebpayServiceImplService(); proxy.Url = "https://tbk.orangepeople.cl/WSWebpayTransaction/cxf/WSWebpayService"; Policy policy = new Policy(); CustomPolicyAssertion customPolicy = new CustomPolicyAssertion(this.IssuerCertificateName, this.TransbankCertificateName); policy.Assertions.Add(customPolicy); proxy.SetPolicy(policy); proxy.Timeout = 60000; proxy.UseDefaultCredentials = false; return proxy; }catch(Exception ex) { throw ParseException(ex); } }
private static void Main(string[] args) { var dwelling = new Dwelling {Address = "1 Main Street, New York, NY", Type = DwellingTypes.SingleHouse}; var dwelling2 = new Dwelling {Address = "2 Main Street, New York, NY", Type = DwellingTypes.SingleHouse}; var policy1 = new Policy {Name = "Silver", PolicyType = PolicyTypes.Home, Price = 1200, Dwelling = dwelling}; var policy2 = new Policy {Name = "Gold", PolicyType = PolicyTypes.Home, Price = 2300, Dwelling = dwelling2}; var customer1 = new Customer {Name = "John Do", Age = 22, Sex = SexTypes.Male, Policy = policy1}; var customer2 = new Customer {Name = "Emily Brown", Age = 32, Sex = SexTypes.Female, Policy = policy2}; var repository = new RuleRepository(); repository.Load("Test", x => x.From(typeof (Program).Assembly)); var ruleSets = repository.GetRuleSets(); IRuleCompiler compiler = new RuleCompiler(); ISessionFactory factory = compiler.Compile(ruleSets); ISession session = factory.CreateSession(); session.Insert(policy1); session.Insert(policy2); session.Insert(customer1); session.Insert(customer2); session.Insert(dwelling); session.Insert(dwelling2); customer1.Age = 10; session.Update(customer1); session.Retract(customer2); session.Fire(); session.Insert(customer2); session.Fire(); customer1.Age = 30; session.Update(customer1); session.Fire(); }
private async Task <string> CallTvMazeApi(string apiUrl) { HttpStatusCode[] httpStatusCodesWorthRetrying = { HttpStatusCode.TooManyRequests, //429 HttpStatusCode.RequestTimeout, // 408 HttpStatusCode.InternalServerError, // 500 HttpStatusCode.BadGateway, // 502 HttpStatusCode.ServiceUnavailable, // 503 HttpStatusCode.GatewayTimeout // 504 }; var response = await Policy .Handle <HttpRequestException>() .OrResult <HttpResponseMessage>(r => httpStatusCodesWorthRetrying.Contains(r.StatusCode)) .WaitAndRetryAsync(4, i => TimeSpan.FromSeconds(i * 2)) .ExecuteAsync(() => _httpClient.GetAsync(apiUrl)); var content = await response.Content.ReadAsStringAsync(); return(content); }
public static void WaitAndRetry() { var random = new Random(); // Policy<> 泛型定义返回值类型, 如若不需要返回值, 可直接使用 Policy var obj = Policy <object> // Handle<> 可指定需要处理的异常类型 .Handle <Exception>() //也可以使用重载对Exception 进行再次过滤 //.Handle<Exception>(e => e is NotSupportedException) .WaitAndRetry(5, // 设置 Sleep Duration Provider 来提供延迟时间 retryTimes => TimeSpan.FromSeconds(Math.Pow(2, retryTimes)), (res, delay, times, context) => { //当委托的代码块执行失败时会进入此 Action, //这里可以对抛出的异常进行日志或其他处理 Console.WriteLine($"retry {times}th times, sleep: {delay.TotalSeconds}s, ex: {res.Exception?.Message}"); }) .Execute(() => { var val = random.Next(0, 100); switch (val % 3) { case 0: return("Success"); default: throw new Exception($"random val: {val}"); } }); Console.WriteLine(obj); }
private async Task <T> CircuitBreakerInner <T>(Func <Task <T> > func, int numberValidRetry, int secondsWait, Action <Exception, TimeSpan, Context> onBreak = null, Action onHalfOpen = null, Action <Context> onReset = null) { var sleepDurationProvider = new Func <int, TimeSpan>((i => TimeSpan.FromSeconds(secondsWait))); var retry = Policy.Handle <Exception>() .WaitAndRetryAsync(numberValidRetry + 1, sleepDurationProvider); var onBreakInner = new Action <Exception, TimeSpan, Context>((ex, t, c) => Console.WriteLine($"Circuit went into a fault state with the exception ({(ex.InnerException ?? ex).Message}) retrying in {t:g})")); var onResetInner = new Action <Context>(context => Console.WriteLine($"Circuit left the fault state")); var onHalfOpenInner = new Action(() => Console.WriteLine("Half Open")); var circuitBreakerPolicy = Policy.Handle <Exception>().CircuitBreakerAsync(numberValidRetry, TimeSpan.FromSeconds(secondsWait), onBreak ?? onBreakInner, onReset ?? onResetInner, onHalfOpen ?? onHalfOpenInner); return(await retry.WrapAsync(circuitBreakerPolicy).ExecuteAsync <T>(func)); }
private async Task <Acknowledgement> TryHandleAsync <TMessage>(TMessage message, CorrelationContext correlationContext, Func <Task> handle) { var currentRetry = 0; var retryPolicy = Policy .Handle <Exception>() .WaitAndRetryAsync(_retries, i => TimeSpan.FromSeconds(_retryInterval)); var messageName = message.GetType().Name; return(await retryPolicy.ExecuteAsync <Acknowledgement>(async() => { var retryMessage = currentRetry == 0 ? string.Empty : $"Retry: {currentRetry}'."; var messageType = message is IEvent ? "n event" : " command"; _logger.LogInformation($"[Handled a{messageType}] : '{messageName}' " + $"Correlation id: '{correlationContext.CorrelationId}'. {retryMessage}"); await handle(); return new Ack(); })); }
/// <summary> /// 添加名单 /// </summary> /// <param name="rosterType">名单类型</param> /// <param name="policy">策略</param> /// <param name="policyKey">策略Key</param> /// <param name="expiry">过期时间</param> /// <param name="item">项目</param> /// <remarks>因为要保存过期时间,所以名单通过Redis 有序集合(sorted set)来存储,score来存储过期时间Ticks</remarks> public async Task AddRosterAsync(RosterType rosterType, string api, Policy policy, string policyKey, TimeSpan?expiry, params string[] item) { if (item == null || item.Length == 0) { return; } //过期时间计算 double score = expiry == null ? double.PositiveInfinity : DateTime.Now.Add(expiry.Value).Ticks; SortedSetEntry[] values = new SortedSetEntry[item.Length]; for (int i = 0; i < item.Length; i++) { values[i] = new SortedSetEntry(item[i], score); } var key = FromatRosterKey(rosterType, api, policy, policyKey); //保存 await _db.SortedSetAddAsync(key, values); //删除过期名单数据 await _db.SortedSetRemoveRangeByScoreAsync(key, 0, DateTime.Now.Ticks, Exclude.Both); }
public async Task <IEventTransmitter> CreateTransmitter(string segmentId, CameraType cameraId) { var iotHubOwnerConnectionString = _configurationReader.GetConfigValue <string>("IOTHUB_OWNER_CONNECTIONSTRING", true); try { var policy = Policy .Handle <TimeoutException>() .Or <DeviceMessageLockLostException>() .Or <IotHubCommunicationException>() .Or <IotHubThrottledException>() .Or <ServerBusyException>() .WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (exception, span, retryCount, context) => { _logger.Warn(exception, $"Retry {retryCount}/{5} sending to IoT Hub, because of exception {exception}"); }); // Retry maximum 5 times with exponential backoff for the above exceptions return(await policy.ExecuteAsync(async() => { var iotHubServiceClient = RegistryManager.CreateFromConnectionString(iotHubOwnerConnectionString); string deviceId = $"{segmentId}-{cameraId}"; var camDevice = await iotHubServiceClient.GetDeviceAsync(deviceId) ?? await iotHubServiceClient.AddDeviceAsync(new Device(deviceId)); var deviceConnectionString = $"HostName={GetIoTHubUri(iotHubOwnerConnectionString)};DeviceId={deviceId};SharedAccessKey={camDevice.Authentication.SymmetricKey.PrimaryKey}"; if (cameraId == CameraType.Camera1) { ConfigurationCache.CacheValue("deviceConnectionString", deviceConnectionString); } return new IoTHubTransmitter(deviceConnectionString); })); } catch (Exception e) { _logger.Error(e, $"An error occurred when trying read device on IoT Hub: {e.Message}"); throw; } }
// RimWorld.Planet.CaravanInventoryUtility public static bool _TryGetBestFood(Caravan caravan, Pawn forPawn, out Thing food, out Pawn owner) { List <Thing> list = RimWorld.Planet.CaravanInventoryUtility.AllInventoryItems(caravan) .Where(arg => CaravanPawnsNeedsUtility.CanNowEatForNutrition(arg.def, forPawn)).ToList(); Thing thing = null; Policy policy = forPawn.GetPolicyAssignedTo(); var foodsForPawn = FoodUtility.MakeRatedFoodListFromThingList(list, forPawn, forPawn, forPawn.GetPolicyAssignedTo()) .Where(arg => RimWorld.Planet.CaravanPawnsNeedsUtility.CanNowEatForNutrition(arg.FoodSource.def, forPawn) && policy.PolicyAllows(forPawn, arg.FoodSource) ); var foodEntry = foodsForPawn.FirstOrDefault(); if (foodEntry != null) { thing = foodsForPawn.FirstOrDefault().FoodSource; } else { thing = null; } if (thing != null) { #if DEBUG Log.Message("Caravan: best food for " + forPawn + " = " + thing); #endif food = thing; owner = RimWorld.Planet.CaravanInventoryUtility.GetOwnerOf(caravan, thing); return(true); } #if DEBUG Log.Message("Caravan: no food found for " + forPawn); #endif food = null; owner = null; return(false); }
/// <summary> /// Sends an HTTP request with a timeout. /// </summary> /// <param name="http"></param> /// <param name="message"></param> /// <param name="timeout"></param> /// <param name="cancelToken"></param> /// <returns></returns> /// <exception cref="TimeoutException">Thrown when the timeout expires.</exception> public static async Task <HttpResponseMessage> SendAsync(this HttpClient http, HttpRequestMessage message, TimeSpan timeout, CancellationToken cancelToken) { // If we were given CancellationToken.None, then use our own. var timeoutCancelTokenSrc = default(CancellationTokenSource); if (cancelToken == CancellationToken.None) { timeoutCancelTokenSrc = new CancellationTokenSource(); cancelToken = timeoutCancelTokenSrc.Token; } try { return(await Policy.TimeoutAsync(timeout) .ExecuteAsync(async token => await http.SendAsync(message, token), cancelToken)); } catch (Polly.Timeout.TimeoutRejectedException timeoutError) { timeoutCancelTokenSrc?.Cancel(); throw new TimeoutException(timeoutError.Message, timeoutError); } }
public void Should_call_ontimeout_with_configured_timeout__pessimistic() { TimeSpan timeoutPassedToConfiguration = TimeSpan.FromMilliseconds(250); TimeSpan?timeoutPassedToOnTimeout = null; Func <Context, TimeSpan, Task, Task> onTimeoutAsync = (ctx, span, task) => { timeoutPassedToOnTimeout = span; return(TaskHelper.EmptyTask); }; var policy = Policy.TimeoutAsync <ResultPrimitive>(timeoutPassedToConfiguration, TimeoutStrategy.Pessimistic, onTimeoutAsync); policy.Awaiting(async p => await p.ExecuteAsync(async() => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None).ConfigureAwait(false); return(ResultPrimitive.WhateverButTooLate); })) .ShouldThrow <TimeoutRejectedException>(); timeoutPassedToOnTimeout.Should().Be(timeoutPassedToConfiguration); }
public void Should_call_fallbackAction_with_the_fault_when_execute_and_capture() { DelegateResult <ResultPrimitive> fallbackOutcome = null; Func <DelegateResult <ResultPrimitive>, Context, CancellationToken, ResultPrimitive> fallbackAction = (outcome, ctx, ct) => { fallbackOutcome = outcome; return(ResultPrimitive.Substitute); }; Action <DelegateResult <ResultPrimitive>, Context> onFallback = (ex, ctx) => { }; FallbackPolicy <ResultPrimitive> fallbackPolicy = Policy <ResultPrimitive> .HandleResult(ResultPrimitive.Fault) .Fallback(fallbackAction, onFallback); var result = fallbackPolicy.ExecuteAndCapture(() => ResultPrimitive.Fault); result.Should().NotBeNull(); result.Result.Should().Be(ResultPrimitive.Substitute); fallbackOutcome.Should().NotBeNull(); fallbackOutcome.Exception.Should().BeNull(); fallbackOutcome.Result.Should().Be(ResultPrimitive.Fault); }
/// <summary> /// Initializes a new instance of the <see cref="PostSearchService"/> class. /// </summary> /// <param name="optionsAccessor">A set of key/value application configuration properties.</param> /// <param name="postStorageProvider">Post storage provider dependency injection.</param> /// <param name="logger">Instance to send logs to the Application Insights service.</param> /// <param name="searchServiceClient">Search service client dependency injection.</param> /// <param name="searchIndexClient">Search index client dependency injection.</param> public PostSearchService( IOptions <SearchServiceSetting> optionsAccessor, IPostStorageProvider postStorageProvider, ILogger <PostSearchService> logger, ISearchServiceClient searchServiceClient, ISearchIndexClient searchIndexClient) { optionsAccessor = optionsAccessor ?? throw new ArgumentNullException(nameof(optionsAccessor)); this.options = optionsAccessor.Value; var searchServiceValue = this.options.SearchServiceName; this.initializeTask = new Lazy <Task>(() => this.InitializeAsync()); this.postStorageProvider = postStorageProvider; this.logger = logger; this.searchServiceClient = searchServiceClient; this.searchIndexClient = searchIndexClient; this.retryPolicy = Policy.Handle <CloudException>( ex => (int)ex.Response.StatusCode == StatusCodes.Status409Conflict || (int)ex.Response.StatusCode == StatusCodes.Status429TooManyRequests) .WaitAndRetryAsync(Backoff.LinearBackoff(TimeSpan.FromMilliseconds(2000), 2)); }
private AsyncRetryPolicy<IConnection> CreateConnectionRetryPolicy(IRecoveryPolicy recoveryPolicy) { return Policy<IConnection> .Handle<Exception>() .WaitAndRetryAsync(recoveryPolicy.RetryCount, (retryAttempt, context) => { context.SetRetryCount(retryAttempt); return recoveryPolicy.GetDelay(retryAttempt); }, (result, _, context) => { var retryCount = context.GetRetryCount(); var endpoint = GetCurrentEndpoint(context); if (result.Exception != null) { Log.FailedToEstablishConnection(_logger, endpoint, retryCount, result.Exception); } else { Log.ConnectionEstablished(_logger, endpoint, retryCount); } }); }
private void btnFallbackPlusWaitAndRetry_Click(object sender, EventArgs e) { var fallbackPolicy = Policy .Handle <MyException>(ex => ex.Message == "temporary-problem") .Fallback((result, context) => { }, (result, context) => { throw new DbNotAvailableException(result); }); var genericDBRetrayPolicy = Policy .Handle <Exception>() .WaitAndRetry( retryCount: 2, sleepDurationProvider: (retryAttempt) => TimeSpan.FromSeconds(5), onRetry: (exception, delay, retrycount, context) => { Debug.WriteLine("genericDBRetrayPolicy: onRetry"); } ); //var policy = Policy.Wrap(genericDBRetrayPolicy, fallbackPolicy); var policy = Policy.Wrap(fallbackPolicy, genericDBRetrayPolicy); /*fallbackPolicy.Execute(() => * { * throw new MyException("temporary-problem"); * });*/ /*genericDBRetrayPolicy.Execute(() => * { * throw new MyException("temporary-problem"); * });*/ policy.Execute(() => { throw new MyException("temporary-problem"); }); }
public async void Should_create_new_context_for_each_call_to_execute_and_capture() { string contextValue = null; RetryPolicy <ResultPrimitive> policy = Policy .HandleResult(ResultPrimitive.Fault) .RetryAsync((_, __, context) => contextValue = context["key"].ToString()); await policy.RaiseResultSequenceOnExecuteAndCaptureAsync( new { key = "original_value" }.AsDictionary(), ResultPrimitive.Fault, ResultPrimitive.Good ).ConfigureAwait(false); contextValue.Should().Be("original_value"); await policy.RaiseResultSequenceOnExecuteAndCaptureAsync( new { key = "new_value" }.AsDictionary(), ResultPrimitive.Fault, ResultPrimitive.Good ).ConfigureAwait(false); contextValue.Should().Be("new_value"); }
public async Task <string> Get() { const string url = "https://www.google.com"; // normally this would be defined more centrally but including here for a quick example var retryPolicy = Policy .Handle <HttpRequestException>() .WaitAndRetryAsync(2, retryCount => TimeSpan.FromSeconds(2), (exception, timeSpan, retryCount, context) => { _logger.LogWarning( $"Call to {url} failed - Retry {retryCount} : TimeSpan {timeSpan} : Ex {exception.Message}"); }); var response = await retryPolicy.ExecuteAsync(() => { var request = new HttpRequestMessage(HttpMethod.Get, url); return(_httpClientWrapper.SendAsync(request)); }); return(response.IsSuccessStatusCode ? "ok" : "not ok"); }
public static async Task RunAsync(string connectionString, ILoggerFactory loggerFactory = null, CancellationToken cancellationToken = default) { var logger = loggerFactory?.CreateLogger <MigrationsLogger>(); await Policy .Handle <SqlException>() .WaitAndRetryAsync( 5, retryAttempt => { var value = Math.Pow(2, retryAttempt) / 4; var randomValue = new Random().Next((int)value * 3, (int)value * 5); logger?.LogInformation("Retrying after {Seconds} seconds...", randomValue); return(TimeSpan.FromSeconds(randomValue)); }) .ExecuteAsync(async ct => { logger?.LogInformation("Running EF Migrations."); await RunInternal(connectionString, loggerFactory, ct); }, cancellationToken); }
public void Should_call_ontimeout_with_timeout_supplied_different_for_each_execution_by_evaluating_func__pessimistic(int programaticallyControlledDelay) { Func <TimeSpan> timeoutFunc = () => TimeSpan.FromMilliseconds(25 * programaticallyControlledDelay); TimeSpan?timeoutPassedToOnTimeout = null; Func <Context, TimeSpan, Task, Task> onTimeoutAsync = (ctx, span, task) => { timeoutPassedToOnTimeout = span; return(TaskHelper.EmptyTask); }; var policy = Policy.TimeoutAsync <ResultPrimitive>(timeoutFunc, TimeoutStrategy.Pessimistic, onTimeoutAsync); policy.Awaiting(async p => await p.ExecuteAsync(async() => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), CancellationToken.None).ConfigureAwait(false); return(ResultPrimitive.WhateverButTooLate); })) .ShouldThrow <TimeoutRejectedException>(); timeoutPassedToOnTimeout.Should().Be(timeoutFunc()); }
public async Task <Block <T> > MineBlock( PrivateKey miner, DateTimeOffset?timestamp = null, bool?append = null, long?maxBlockBytes = null, int?maxTransactions = null, int?maxTransactionsPerSigner = null, IComparer <Transaction <T> > txPriority = null, CancellationToken?cancellationToken = null) => #pragma warning disable SA1118 await MineBlock( miner : miner, timestamp : timestamp ?? DateTimeOffset.UtcNow, append : append ?? true, maxBlockBytes : maxBlockBytes ?? Policy.GetMaxBlockBytes(Count), maxTransactions : maxTransactions ?? Policy.GetMaxTransactionsPerBlock(Count), maxTransactionsPerSigner : maxTransactionsPerSigner ?? Policy.GetMaxTransactionsPerSignerPerBlock(Count), txPriority : txPriority, cancellationToken : cancellationToken ?? default(CancellationToken));
public async Task <string> PostAsync() { var retryPolicy = _policyRegistry.Get <IAsyncPolicy <HttpResponseMessage> >(PolicyNames.RetryWithLogging) ?? Policy.NoOpAsync <HttpResponseMessage>(); var context = new Context( $"{ContextNames.Logger}-{Guid.NewGuid()}", new Dictionary <string, object> { { ContextNames.Logger, _logger } }); var request = new HttpRequestMessage(HttpMethod.Post, "/players"); request.Content = new JsonContent <Player>(new Player { FirstName = "Olek", LastName = "Malinowski" }, new JsonSerializerOptions { WriteIndented = true, PropertyNameCaseInsensitive = true }); _logger.LogWarning("URL Receiving: {0}", _client.BaseAddress.ToString()); var response = await _client.PostJsonHttpClient("/players", new Player { FirstName = "Olek", LastName = "Malinowski" }); //var respose = await _client.PostAsync("/players", new JsonContent( // new Player {FirstName = "Olek", LastName = "Malinowski"}, new JsonSerializerOptions // { // WriteIndented = true, // PropertyNameCaseInsensitive = true // })); //var response = await _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); //var response = await retryPolicy.ExecuteAsync(ctx => _client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead), context); //return string.Empty; return(response.IsSuccessStatusCode ? await response.Content.ReadAsStringAsync() : "Error"); }
public void Should_call_ontimeout_but_not_with_task_wrapping_abandoned_action__optimistic() { Task taskPassedToOnTimeout = null; Func <Context, TimeSpan, Task, Task> onTimeoutAsync = (ctx, span, task) => { taskPassedToOnTimeout = task; return(TaskHelper.EmptyTask); }; TimeSpan timeout = TimeSpan.FromMilliseconds(250); var policy = Policy.TimeoutAsync <ResultPrimitive>(timeout, TimeoutStrategy.Optimistic, onTimeoutAsync); var userCancellationToken = CancellationToken.None; policy.Awaiting(async p => await p.ExecuteAsync(async ct => { await SystemClock.SleepAsync(TimeSpan.FromSeconds(3), ct).ConfigureAwait(false); return(ResultPrimitive.WhateverButTooLate); }, userCancellationToken).ConfigureAwait(false)) .ShouldThrow <TimeoutRejectedException>(); taskPassedToOnTimeout.Should().BeNull(); }
/** * Converts the specified AWS policy object to a JSON string, suitable for * passing to an AWS service. * * @param policy * The AWS policy object to convert to a JSON string. * * @return The JSON string representation of the specified policy object. * * @throws IllegalArgumentException * If the specified policy is null or invalid and cannot be * serialized to a JSON string. */ public string WritePolicyToString(Policy policy) { if (policy == null) { throw new ArgumentNullException("Policy cannot be null"); } StringWriter writer = new StringWriter(); try { JsonWriter generator = new JsonWriter(writer); generator.PrettyPrint = true; generator.IndentValue = 4; writePolicy(policy, generator); return writer.ToString().Trim(); } catch (Exception e) { string message = "Unable to serialize policy to JSON string: " + e.Message; throw new ArgumentException(message, e); } }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionPolicyFactory"/> class. /// Use if you need to inject a test logger /// </summary> /// <param name="connection"></param> /// <param name="logger">The logger.</param> public ConnectionPolicyFactory(RmqMessagingGatewayConnection connection, ILog logger) { _logger = logger; int retries = connection.AmpqUri.ConnectionRetryCount; int retryWaitInMilliseconds = connection.AmpqUri.RetryWaitInMilliseconds; int circuitBreakerTimeout = connection.AmpqUri.CircuitBreakTimeInMilliseconds; RetryPolicy = Policy.Handle <BrokerUnreachableException>() .Or <Exception>() .WaitAndRetry( retries, retryAttempt => TimeSpan.FromMilliseconds(retryWaitInMilliseconds * Math.Pow(2, retryAttempt)), (exception, timeSpan, context) => { if (exception is BrokerUnreachableException) { _logger.WarnException( "RMQMessagingGateway: BrokerUnreachableException error on connecting to queue {0} exchange {1} on connection {2}. Will retry {3} times", exception, context["queueName"], connection.Exchange.Name, connection.AmpqUri.GetSanitizedUri(), retries); } else { logger.WarnException( "RMQMessagingGateway: Exception on connection to queue {0} via exchange {1} on connection {2}", exception, context["queueName"], connection.Exchange.Name, connection.AmpqUri.GetSanitizedUri()); throw exception; } }); CircuitBreakerPolicy = Policy.Handle <BrokerUnreachableException>().CircuitBreaker(1, TimeSpan.FromMilliseconds(circuitBreakerTimeout)); }
/** * Converts the specified AWS policy object to a JSON string, suitable for * passing to an AWS service. * * @param policy * The AWS policy object to convert to a JSON string. * * @return The JSON string representation of the specified policy object. * * @throws IllegalArgumentException * If the specified policy is null or invalid and cannot be * serialized to a JSON string. */ public string WritePolicyToString(Policy policy) { if (policy == null) { throw new ArgumentNullException("Policy cannot be null"); } StringWriter writer = new StringWriter(); try { JsonWriter generator = new JsonTextWriter(writer); generator.Formatting = Formatting.Indented; writePolicy(policy, generator); generator.Flush(); return writer.ToString(); } catch (Exception e) { string message = "Unable to serialize policy to JSON string: " + e.Message; throw new ArgumentException(message, e); } }
public async Task InitializeAsync() { try { _eventStoreCluster.Start(); } catch (FluentDockerException) { // don't know why, sometimes the default network (e.g. net50_default) remains // from previous cluster and prevents docker-compose up from executing successfully BuildCluster().Dispose(); _eventStoreCluster.Start(); } try { using var httpClient = new HttpClient(new HttpClientHandler { ServerCertificateCustomValidationCallback = delegate { return(true); } }) { BaseAddress = new UriBuilder { Port = 2113, Scheme = Uri.UriSchemeHttps }.Uri }; await Policy.Handle <Exception>() .WaitAndRetryAsync(5, retryCount => TimeSpan.FromSeconds(retryCount * retryCount)) .ExecuteAsync(async() => { using var response = await httpClient.GetAsync("/health/live"); if (response.StatusCode >= HttpStatusCode.BadRequest) { throw new Exception($"Health check failed with status code: {response.StatusCode}."); } }); } catch (Exception) { _eventStoreCluster.Dispose(); throw; } await Connection.ConnectAsync(); }
/// <summary> /// Insertpolicy - them thông tin policy /// </summary> /// <param name="policy"></param> /// <returns></returns> public bool InsertPolicy(Policy policy) { SqlParameter[] paramList = new SqlParameter[3]; paramList[0] = new SqlParameter("@PolicyType", SqlDbType.NVarChar, 256); paramList[0].Value = policy.PolicyType; paramList[1] = new SqlParameter("@PolicyContent", SqlDbType.NVarChar); paramList[1].Value = policy.PolicyContent; paramList[2] = new SqlParameter("@StatusId", SqlDbType.NVarChar, 256); paramList[2].Value = policy.StatusId; if (db.executeUpdate("InsertPolicy", paramList) == 0) { return(false); } else { return(true); } }
private Policy[] CreatePolicies(string origin) { return(new Policy[] { Policy.Handle <HttpRequestException>() .WaitAndRetryAsync(//必须使用WaitAndRetryAsync方法,不能使用WaitAndRetry方法,否则,提示“Please use asynchronous-defined policies when calling asynchronous ExecuteAsync”错误,导致无法完成对API的请求(400) // number of retries _retryCount, // exponential backofff retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), // on retry (exception, timeSpan, retryCount, context) => { var msg = $"第{retryCount}次重试 implemented with Polly's RetryPolicy " + $"of {context.PolicyKey} " + $"at {context.ExecutionKey}, " + $"due to: {exception}."; _logger.LogWarning(msg); _logger.LogDebug(msg); }), Policy.Handle <HttpRequestException>() .CircuitBreakerAsync( // number of exceptions before breaking circuit _exceptionCountAllowedBeforeBreaking, // time circuit opened before retry TimeSpan.FromMinutes(1), (exception, duration) => { // on circuit opened _logger.LogWarning("[熔断器打开]Circuit breaker opened"); _logger.LogDebug("[熔断器打开]Circuit breaker opened"); }, () => { // on circuit closed _logger.LogWarning("[熔断器关闭]Circuit breaker opened"); _logger.LogDebug("[熔断器打开]Circuit breaker opened"); }) }); }
public void ImplementRuleYoungestDriver75() { //Assemble Policy policy = _policy; Driver driver = _driver; DateTime startDate = new DateTime(2017, 03, 20); DateTime driverDateOfBirth = new DateTime(1942, 03, 20); policy.PolicyStartDate = startDate; policy.DriversOnPolicy.Add(driver); driver.DateOfBirth = driverDateOfBirth; decimal _basePremium = 500; YoungestDriverRule youngestDriverRule = new YoungestDriverRule(); //Act decimal expectedResult = _basePremium + _basePremium * 0.1m; decimal actualResult = youngestDriverRule.ImplementRule(policy, _basePremium); //Assert Assert.AreEqual(expectedResult, actualResult); }
private async Task LoadFileAsync() { try { await Policy.Handle <JsonSerializationException>() .Or <IOException>() .WaitAndRetryAsync(3, CalcRetryIntervals, (exception, i) => ReportRetry(exception)) .ExecuteAsync(() => { LoadFileCore(); return(Task.CompletedTask); }); } catch (JsonSerializationException e) { ReportJsonError(e); } catch (IOException e) { ReportIOError(e); } }
private async Task CheckForUpdateAsync() { var policy = Policy .Handle <RateLimitExceededException>() .WaitAndRetryAsync(5, retry => TimeSpan.FromSeconds(Math.Pow(2, retry))); await policy.ExecuteAsync(async() => { var release = await GetNewestReleaseAsync(); if (release == null) { _isUpdateAvailable = false; return; } var newestVersion = release.Name.TrimStart('v'); var version = GetCurrentVersion(); _isUpdateAvailable = !string.Equals(newestVersion, version); }); }
private IEnumerable <IAsyncPolicy <IContinuation> > combine(RetryPolicyCollection parent) { foreach (var policy in _policies) { yield return(policy); } if (MaximumAttempts.HasValue) { yield return(Policy <IContinuation> .Handle <Exception>().Requeue(MaximumAttempts.Value)); } foreach (var policy in parent._policies) { yield return(policy); } if (parent.MaximumAttempts.HasValue) { yield return(Policy <IContinuation> .Handle <Exception>().Requeue(parent.MaximumAttempts.Value)); } }
public async void Should_callNextPipelineMiddleware() { //Arrange var dummyPolicy = Policy.Handle <Exception>().RetryAsync(0); var resiliencyMiddleware = new DefaultResiliencyMiddleware( Mock.Of <IResiliencyPolicyProvider>(x => x.GetConcurencyExceptionPolicy(It.IsAny <Action <Exception> >()) == dummyPolicy && x.GetOutOfOrderPolicy(It.IsAny <Action <int> >()) == dummyPolicy), Mock.Of <ILogger <DefaultResiliencyMiddleware> >()); var sentMessage = Mock.Of <IMessage>(); var isNextMiddlewareCalled = false; var envelope = new MessagingEnvelope <IMessage>(new System.Collections.Generic.Dictionary <string, string>(), sentMessage); Task Next() { isNextMiddlewareCalled = true; return(Task.CompletedTask); } //Act await resiliencyMiddleware.Invoke(envelope, default, Next);
protected override Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken cancellationToken) => Policy .Handle <HttpRequestException>() .Or <TaskCanceledException>() .OrResult <HttpResponseMessage>(x => { string result = x.Content.ReadAsStringAsync().GetAwaiter().GetResult(); dynamic array = JsonConvert.DeserializeObject(result); if (array["status"] == "running") { return(true); } else { return(false); } }) .WaitAndRetryAsync(7, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))) .ExecuteAsync(() => base.SendAsync(request, cancellationToken));