// GET: /[email protected] public IHttpActionResult Get(string email) { IEnumerable <string> list; if (!Request.Headers.TryGetValues("x-token", out list)) { return(BadRequest("Un-authorized.")); } var token = list.FirstOrDefault(); if (string.IsNullOrWhiteSpace(token) || EncryptionDecryptionHelper.Decrypt(token) != ConfigurationManager.AppSettings["matchingKey"]) { return(BadRequest("Un-authorized.")); } var maxRetryAttempts = 8; var pauseBetweenFailures = TimeSpan.FromSeconds(2); Console.WriteLine("Starting application.. "); IList <DistributionListModel> distributionList = null; RetryHelper.RetryOnException(maxRetryAttempts, pauseBetweenFailures, () => { distributionList = new List <DistributionListModel>(); ExpandDistributionLists(10, email, distributionList); }); Console.WriteLine("Ending application.. "); return(Ok(distributionList)); }
static void Main(string[] args) { using (var sampleClass = new SamplesClass()) { RetryHelper.RetryOnException(3, 10, // retry method setup to fail twice before setting a variable () => sampleClass.DoSomethingWithErrors(), (e) => { return(e is NullReferenceException); }); Console.WriteLine("Method with no return:"); Console.WriteLine("If this method is successful then it should return a result of 50 and if not then the result will be 0."); Console.WriteLine($"The result is: {sampleClass.assertVariable}"); Console.WriteLine(); } using (var sampleClass = new SamplesClass()) { var result = RetryHelper.RetryOnException <string>(3, 10, // retry method setup to fail twice before returning a value () => sampleClass.DoSomethingWithErrorsWithReturn(), (e) => { return(e is NullReferenceException); }); Console.WriteLine("----------------------------------------"); Console.WriteLine("Method with return:"); Console.WriteLine(result); } Console.ReadKey(); }
public void Instance_AutomaticallyReadFileOnChange() { // Arrange RetryHelper.RetryOnException(5, TimeSpan.FromSeconds(1), () => File.Delete(TelemetryDataRepository.GetStorageFilePath())); var repository = new TelemetryDataRepository(); repository.Data.IsAnonymousDataShared = false; repository.Data.InstallationDate = DateTime.MaxValue; repository.Data.LastSavedAnalysisDate = DateTime.MaxValue; repository.Data.NumberOfDaysOfUse = long.MaxValue; repository.Data.LastUploadDate = DateTime.MaxValue; var otherRepository = new TelemetryDataRepository(); // Act repository.Save(); Task.Delay(700).Wait(); // Assert otherRepository.Data.InstallationDate.Should().Be(DateTime.MaxValue); otherRepository.Data.LastSavedAnalysisDate.Should().Be(DateTime.MaxValue); otherRepository.Data.NumberOfDaysOfUse.Should().Be(long.MaxValue); otherRepository.Data.LastUploadDate.Should().Be(DateTime.MaxValue); otherRepository.Data.IsAnonymousDataShared.Should().BeFalse(); }
public void RetryOnException_WhenGivingZeroTimesRetry_ReturnsFalse() { // Arrange & Act var result = RetryHelper.RetryOnException(0, TimeSpan.Zero, () => { }); // Assert result.Should().BeFalse(); }
public void RetryOnException_WhenOperationSucceed_ReturnsTrue() { // Arrange & Act var result = RetryHelper.RetryOnException(1, TimeSpan.Zero, () => { }); // Assert result.Should().BeTrue(); }
public void RetryOnException_WhenOperationAlwaysFails_ReturnsFalse() { // Arrange & Act var result = RetryHelper.RetryOnException(1, TimeSpan.Zero, () => { throw new Exception(); }); // Assert result.Should().BeFalse(); }
public void Delete() { var heartBeatPath = Path.Combine(Infrastructure.Settings.GetRootStoragePathForLocation(HeartBeatConstants.StorageLoc), GetHeartBeatRelativePath()); RetryHelper.RetryOnException("Deleting heartbeat...", () => { System.IO.File.Delete(heartBeatPath); }, TimeSpan.FromSeconds(1), 3, false); }
private void CreateHeartBeatDirectoryIfNotExists() { var heartBeatFolder = Path.Combine(Infrastructure.Settings.GetRootStoragePathForLocation(HeartBeatConstants.StorageLoc), HeartBeatConstants.HeartBeatFolder); RetryHelper.RetryOnException("Creating heartbeat folder...", () => { FileSystemHelpers.CreateDirectoryIfNotExists(heartBeatFolder); }, TimeSpan.FromMilliseconds(100), 3, false); }
public ActionResult ViewCruise(int id) { Cruise c = null; RetryHelper.RetryOnException(3, TimeSpan.FromSeconds(1), () => { c = db.Cruise.Find(id); }); return(View(c)); }
public void Send() { CreateHeartBeatDirectoryIfNotExists(); var heartBeatPath = Path.Combine(Infrastructure.Settings.GetRootStoragePathForLocation(HeartBeatConstants.StorageLoc), GetHeartBeatRelativePath()); RetryHelper.RetryOnException("Sending heartbeat...", () => { this.ToJsonFile(heartBeatPath); }, TimeSpan.FromMilliseconds(100), 3, false); }
private static void Main(string[] args) { var tentativasMxima = 3; var delayOperacao = TimeSpan.FromSeconds(2); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); RetryHelper.RetryOnException(tentativasMxima, delayOperacao, () => { var x = client.GetAsync("XXXXXXXXXXXX"); }); }
public void Ctor_AlwaysCreateStorageFile() { // Arrange var filePath = TelemetryDataRepository.GetStorageFilePath(); RetryHelper.RetryOnException(5, TimeSpan.FromSeconds(1), () => File.Delete(filePath)); File.Exists(filePath).Should().BeFalse(); // Sanity test // Act var repository = new TelemetryDataRepository(); // Assert File.Exists(filePath).Should().BeTrue(); }
public void Ctor_AlwaysCreateStorageFileFolders() { // Arrange var filePath = TelemetryDataRepository.GetStorageFilePath(); var directoryPath = Path.GetDirectoryName(filePath); RetryHelper.RetryOnException(5, TimeSpan.FromSeconds(1), () => Directory.Delete(directoryPath, true)); Directory.Exists(directoryPath).Should().BeFalse(); // Sanity test // Act var repository = new TelemetryDataRepository(); // Assert Directory.Exists(directoryPath).Should().BeTrue(); }
public static HeartBeat OpenHeartBeat(string heartBeatPath) { try { HeartBeat heartBeat = FileSystemHelpers.FromJsonFile <HeartBeat>(heartBeatPath); return(heartBeat); } catch (Exception) { // possibly a stale heartbeat file which is either empty or in XML format RetryHelper.RetryOnException("Deleting corrupt heartbeat...", () => { System.IO.File.Delete(heartBeatPath); }, TimeSpan.FromSeconds(1), 3, false); return(null); } }
public void RetryOnException_WhenFailsTwiceWithAFiveSecondDelay_ReturnsFalseAndCompletesInTenSeconds() { // Arrange var fiveSecondsInMilliseconds = 5000; var delay = TimeSpan.FromMilliseconds(fiveSecondsInMilliseconds); var timeWatch = new System.Diagnostics.Stopwatch(); // Act timeWatch.Start(); var result = RetryHelper.RetryOnException(2, delay, () => { throw new Exception(); }); timeWatch.Stop(); // Assert result.Should().BeFalse(); timeWatch.ElapsedMilliseconds.Should().BeInRange( (fiveSecondsInMilliseconds * 2) - 500, (fiveSecondsInMilliseconds * 2) + 500); }
/// <summary> /// Delete the given file from all known locations /// </summary> public async Task DeleteFileAsync(string filePath, string blobSasUri, Lease lease = null) { if (!string.IsNullOrWhiteSpace(blobSasUri)) { var fileBlob = BlobController.GetBlobForFile(filePath, blobSasUri); await fileBlob.DeleteIfExistsAsync(DeleteSnapshotsOption.None, GetAccessCondition(lease), null, null); } foreach (var baseDir in new string[] { Infrastructure.Settings.TempDir, Settings.UserSiteStorageDirectory }) { string fullPath = Path.Combine(baseDir, filePath); if (System.IO.File.Exists(fullPath)) { RetryHelper.RetryOnException("Deleting file asynchronously...", () => { System.IO.File.Delete(fullPath); }, TimeSpan.FromSeconds(1)); } } }
public void RetryOnExceptionTest() { var times = 2; var @thisInt = 0; //no ex var @this = RetryHelper.RetryOnException <int, NotSupportedException>(times, (a) => { return(GetNotSupportedValues(false)); }, (i, e) => { }); Assert.AreEqual(@this, 10086); // ex @this = 0; @thisInt = 0; @this = RetryHelper.RetryOnException <int, MissingFieldException>(times, (a) => { return(GetMissingFieldValues(true)); }, (i, e) => { @thisInt += i; }); Assert.AreEqual(@this, 0); Assert.AreEqual(@thisInt, 3); // ex ,other ex @this = 0; @thisInt = 0; @this = RetryHelper.RetryOnException <int, NotSupportedException>(times, (a) => { return(GetMissingFieldValues(true)); }, (i, e) => { @thisInt += i; }); Assert.AreEqual(@this, 0); Assert.AreEqual(@thisInt, 0); }
private void MoveFileOnDisk(string oldPath, string newPath, StorageLocation location) { string baseDir = GetRootStoragePathForWhenBlobStorageIsNotConfigured(location); string oldFullPath = Path.Combine(baseDir, oldPath); string newFullPath = Path.Combine(baseDir, newPath); if (oldFullPath.Equals(newFullPath, StringComparison.OrdinalIgnoreCase)) { // Moving file from and to the same location. Don't do anything return; } Logger.LogDiagnostic("Moving file from {0} to {1}", oldFullPath, newFullPath); Directory.CreateDirectory(Path.GetDirectoryName(newFullPath)); if (!System.IO.File.Exists(oldFullPath)) { // Source file doesn't exist throw new FileNotFoundException(oldPath); } if (System.IO.File.Exists(newFullPath)) { // File.Move doesn't work if the destination file already exists Logger.LogDiagnostic("Deleting preexisting file {0}", newFullPath); RetryHelper.RetryOnException("Deleting preexisting...", () => { System.IO.File.Delete(newFullPath); }, TimeSpan.FromSeconds(1)); } System.IO.File.Move(oldFullPath, newFullPath); if (System.IO.File.Exists(oldFullPath)) { // If the source file is in use File.Move doesn't delete it Logger.LogDiagnostic("The source file wasn't deleted (it may have been in use). Let's delete it now"); RetryHelper.RetryOnException("Deleting old path while moving files on disk...", () => { System.IO.File.Delete(oldFullPath); }, TimeSpan.FromSeconds(1)); } }
private static ActionResult _installStateTool(Session session, out string stateToolPath) { Error.ResetErrorDetails(session); var paths = GetPaths(); string stateURL = "https://state-tool.s3.amazonaws.com/update/state/release/"; string jsonURL = stateURL + paths.JsonDescription; string timeStamp = DateTime.Now.ToFileTime().ToString(); string tempDir = Path.Combine(Path.GetTempPath(), timeStamp); string stateToolInstallDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ActiveState", "bin"); stateToolPath = Path.Combine(stateToolInstallDir, "state.exe"); if (File.Exists(stateToolPath)) { session.Log("Using existing State Tool executable at install path"); Status.ProgressBar.Increment(session, 200); return ActionResult.Success; } session.Log(string.Format("Using temp path: {0}", tempDir)); try { Directory.CreateDirectory(tempDir); } catch (Exception e) { string msg = string.Format("Could not create temp directory at: {0}, encountered exception: {1}", tempDir, e.ToString()); session.Log(msg); RollbarReport.Critical(msg, session); return ActionResult.Failure; } ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; string versionInfoString = "unset"; session.Log(string.Format("Downloading JSON from URL: {0}", jsonURL)); try { RetryHelper.RetryOnException(session, 3, TimeSpan.FromSeconds(2), () => { var client = new WebClient(); versionInfoString = client.DownloadString(jsonURL); }); } catch (WebException e) { string msg = string.Format("Encountered exception downloading state tool json info file: {0}", e.ToString()); session.Log(msg); new NetworkError().SetDetails(session, e.Message); return ActionResult.Failure; } VersionInfo info; try { info = JsonConvert.DeserializeObject<VersionInfo>(versionInfoString); } catch (Exception e) { string msg = string.Format("Could not deserialize version info. Version info string {0}, exception {1}", versionInfoString, e.ToString()); session.Log(msg); RollbarReport.Critical(msg, session); return ActionResult.Failure; } string zipPath = Path.Combine(tempDir, paths.ZipFile); string zipURL = stateURL + info.version + "/" + paths.ZipFile; session.Log(string.Format("Downloading zip file from URL: {0}", zipURL)); Status.ProgressBar.StatusMessage(session, "Downloading State Tool..."); var tokenSource = new CancellationTokenSource(); var token = tokenSource.Token; Task incrementTask = Task.Run(() => { incrementProgressBar(session, 50, token); }); Task<ActionResult> downloadTask = Task.Run(() => { try { RetryHelper.RetryOnException(session, 3, TimeSpan.FromSeconds(2), () => { var client = new WebClient(); client.DownloadFile(zipURL, zipPath); }); } catch (WebException e) { string msg = string.Format("Encountered exception downloading state tool zip file. URL to zip file: {0}, path to save zip file to: {1}, exception: {2}", zipURL, zipPath, e.ToString()); session.Log(msg); new NetworkError().SetDetails(session, e.Message); return ActionResult.Failure; } return ActionResult.Success; }); ActionResult result = downloadTask.Result; tokenSource.Cancel(); incrementTask.Wait(); if (result.Equals(ActionResult.Failure)) { return result; } SHA256 sha = SHA256.Create(); FileStream fInfo = File.OpenRead(zipPath); string zipHash = BitConverter.ToString(sha.ComputeHash(fInfo)).Replace("-", string.Empty).ToLower(); if (zipHash != info.sha256v2) { string msg = string.Format("SHA256 checksum did not match, expected: {0} actual: {1}", info.sha256v2, zipHash.ToString()); session.Log(msg); RollbarReport.Critical(msg, session); return ActionResult.Failure; } Status.ProgressBar.StatusMessage(session, "Extracting State Tool executable..."); Status.ProgressBar.Increment(session, 50); try { ZipFile.ExtractToDirectory(zipPath, tempDir); } catch (Exception e) { string msg = string.Format("Could not extract State Tool, encountered exception. Path to zip file: {0}, path to temp directory: {1}, exception {2})", zipPath, tempDir, e); session.Log(msg); RollbarReport.Critical(msg, session); return ActionResult.Failure; } try { Directory.CreateDirectory(stateToolInstallDir); } catch (Exception e) { string msg = string.Format("Could not create State Tool install directory at: {0}, encountered exception: {1}", stateToolInstallDir, e.ToString()); session.Log(msg); RollbarReport.Critical(msg, session); return ActionResult.Failure; } try { File.Move(Path.Combine(tempDir, paths.ExeFile), stateToolPath); } catch (Exception e) { string msg = string.Format("Could not move State Tool executable to: {0}, encountered exception: {1}", stateToolPath, e); session.Log(msg); RollbarReport.Critical(msg, session); return ActionResult.Failure; } string configDirCmd = " export" + " config" + " --filter=dir"; string output; ActionResult runResult = ActiveState.Command.Run(session, stateToolPath, configDirCmd, out output); session.Log("Writing install file..."); // We do not fail the installation if writing the installsource.txt file fails if (runResult.Equals(ActionResult.Failure)) { string msg = string.Format("Could not get config directory from State Tool"); session.Log(msg); RollbarReport.Error(msg, session); } else { string contents = "msi-ui"; if (session.CustomActionData["UI_LEVEL"] == "2") { contents = "msi-silent"; } try { string installFilePath = Path.Combine(output.Trim(), "installsource.txt"); File.WriteAllText(installFilePath, contents, Encoding.ASCII); } catch (Exception e) { string msg = string.Format("Could not write install file at path: {0}, encountered exception: {1}", output, e.ToString()); session.Log(msg); RollbarReport.Error(msg, session); } } session.Log("Updating PATH environment variable"); Status.ProgressBar.Increment(session, 50); string oldPath = Environment.GetEnvironmentVariable("PATH", EnvironmentVariableTarget.Machine); if (oldPath.Contains(stateToolInstallDir)) { session.Log("State tool installation already on PATH"); } else { var newPath = string.Format("{0};{1}", stateToolInstallDir, oldPath); session.Log(string.Format("updating PATH to {0}", newPath)); try { Environment.SetEnvironmentVariable("PATH", newPath, EnvironmentVariableTarget.Machine); } catch (Exception e) { string msg = string.Format("Could not update PATH. Encountered exception: {0}", e.Message); session.Log(msg); new SecurityError().SetDetails(session, msg); return ActionResult.Failure; } } session.Log("Running prepare step..."); string prepareCmd = " _prepare"; string prepareOutput; ActionResult prepareRunResult = ActiveState.Command.Run(session, stateToolPath, prepareCmd, out prepareOutput); if (prepareRunResult.Equals(ActionResult.Failure)) { string msg = string.Format("Preparing environment caused error: {0}", prepareOutput); session.Log(msg); RollbarReport.Critical(msg, session); Record record = new Record(); var errorOutput = Command.FormatErrorOutput(prepareOutput); record.FormatString = msg; session.Message(InstallMessage.Error | (InstallMessage)MessageBoxButtons.OK, record); return ActionResult.Failure; } else { session.Log(string.Format("Prepare Output: {0}", prepareOutput)); } Status.ProgressBar.Increment(session, 50); return ActionResult.Success; }
public void Init() { RetryHelper.RetryOnException(3, TimeSpan.FromSeconds(10), () => { _driver = DriverFactory.GetDriver(); }); }
public void AfterSuite() { RetryHelper.RetryOnException(2, TimeSpan.FromSeconds(5), () => { _driver?.Quit(); }); }