public void ThenAsyncTOut_WhenExecuteIsNull_ThrowsArgumentNullException() { TryResult t = ""; Func <Task <TryResult <int> > > t2 = null; Assert.ThrowsAsync <ArgumentNullException>(() => t.ThenAsync(t2)); }
public void ToString_WhenSuccess_DoesNotContainError() { var r = TryResult.Succeed(); var s = r.ToString(); Assert.IsFalse(s.Contains("error", StringComparison.InvariantCultureIgnoreCase)); }
public void ThenTryTIn_WhenExecuteIsNull_ThrowsArgumentNullException() { TryResult <int> t = ""; Func <int, TryResult> t2 = null; Assert.Throws <ArgumentNullException>(() => t.ThenTry(t2)); }
void LoginHandler(LoginManagerLoginResult loginResult, NSError error) { if (loginResult.IsCancelled) { _facebookTask.TrySetResult(TryResult.Create(false, new SocialData { LoginState = SocialLoginStateEnum.Canceled })); } else if (error != null) { _facebookTask.TrySetResult(TryResult.Create(false, new SocialData { LoginState = SocialLoginStateEnum.Failed, ErrorString = error.LocalizedDescription })); } else { _socialData = new SocialData { Token = loginResult.Token.TokenString, UserId = loginResult.Token.UserId, ExpireAt = loginResult.Token.ExpirationDate.ToDateTimeUtc() }; _facebookTask.TrySetResult(TryResult.Create(true, _socialData)); } }
public void Fail_WhenErrorMessageHasValue_SetsErrorMessage() { var err = "er"; var r = TryResult.Fail(err); Assert.AreEqual(err, r.ErrorMessage); }
private TryResult <string> _ValueSectionName(bool isApp, bool isLoaded, string appPrefix, string drvPrefix, string identSectionName) { if (isLoaded) { return(TryResult <string> .Failed); } string prefix = isApp ? appPrefix : drvPrefix; if (!String.IsNullOrEmpty(prefix)) { if (identSectionName.StartsWith(appPrefix)) { identSectionName = identSectionName.Substring(appPrefix.Length); } if (identSectionName.StartsWith(drvPrefix)) { identSectionName = identSectionName.Substring(drvPrefix.Length); } return(TryResult <string> .FromResult(prefix + identSectionName)); } return(TryResult <string> .Failed); }
public static async Task <TryResult <T> > TryExecuteAndReadResponse <T>(this Task <HttpResponseMessage> send, string httpMethod, string url, AhkResult ahkResult, bool allowNotFound = false, Predicate <HttpResponseMessage> responseAdditionalCheck = null) { var requestMethodAndUrl = $"{httpMethod.ToUpperInvariant()} {url}"; HttpResponseMessage responseMessage; try { responseMessage = await send; } catch (Exception ex) { ahkResult.AddProblem(ex, $"{requestMethodAndUrl} keres sikertelen. {requestMethodAndUrl} request unsuccessful."); return(TryResult <T> .Failed()); } if (responseAdditionalCheck != null) { if (!responseAdditionalCheck(responseMessage)) { return(TryResult <T> .Failed()); } } if (allowNotFound && responseMessage.StatusCode == System.Net.HttpStatusCode.NotFound) { return(TryResult <T> .Ok(default(T))); } return(await responseMessage.TryReadResponse <T>(ahkResult)); }
public void DeletePicturesCommand_ShouldOnlyRemoveSelectedPictures_WhenYesIsPressed() { _mockModalDialog.Setup(dialog => dialog.ShowQuestion(It.IsAny <string>(), It.IsAny <string>())) .Returns(true); var tryResult = new TryResult(); tryResult.Try(() => { }); _mockPictureRepository.Setup(repo => repo.TryDelete(It.IsAny <string>())) .Returns(tryResult); var picturesExist = new Dictionary <Guid, bool>(); for (var i = 0; i < 3; i++) { var picture = new Picture(new BitmapImage(), string.Empty); _pictureGridViewModel.Pictures.Add(picture); // All odd numbers should not exist. picturesExist.Add(picture.Guid, !(i % 2 == 0)); } var picturesToRemove = _pictureGridViewModel.Pictures.ToList().FindAll(pic => { var picturesThatDontExist = picturesExist.Where(picExist => picExist.Value == false) .ToDictionary(key => key.Key); return(picturesThatDontExist.ContainsKey(pic.Guid)); }); _pictureGridViewModel.DeletePicturesCommand.Execute(picturesToRemove); Assert.IsTrue(picturesExist.All(pic => { return(pic.Value ? _pictureGridViewModel.Pictures.SingleOrDefault(oPic => oPic.Guid == pic.Key) != null : _pictureGridViewModel.Pictures.SingleOrDefault(oPic => oPic.Guid == pic.Key) == null); })); }
public TryResult ChangeFileName(string sourceFileName, string destinationFileName) { var tryResult = new TryResult(); tryResult.Try(() => File.Move(sourceFileName, destinationFileName)); return(tryResult); }
public static async Task <TryResult <TResult> > TryReadResponse <TResult>(this HttpResponseMessage httpResponse, AhkResult ahkResult) { var requestMethodAndUrl = $"{httpResponse.RequestMessage.Method.Method.ToUpperInvariant()} {httpResponse.RequestMessage.RequestUri}"; if (!httpResponse.IsSuccessStatusCode) { ahkResult.AddProblem($"{requestMethodAndUrl} hibas valaszkod {httpResponse.StatusCode}. {requestMethodAndUrl} yields invalid response {httpResponse.StatusCode}."); return(TryResult <TResult> .Failed()); } try { var value = await httpResponse.Content.ReadAsAsync <TResult>(); if (value == null) { ahkResult.AddProblem($"{requestMethodAndUrl} valasz tartalma hibas. {requestMethodAndUrl} yields invalid content."); return(TryResult <TResult> .Failed()); } return(TryResult <TResult> .Ok(value)); } catch (Exception ex) { ahkResult.AddProblem(ex, $"{requestMethodAndUrl} valasz tartalma hibas. {requestMethodAndUrl} yields invalid content."); return(TryResult <TResult> .Failed()); } }
public TryResult DeleteFile(string fileName) { var tryResult = new TryResult(); tryResult.Try(() => File.Delete(fileName)); return(tryResult); }
public void Succeed_SetsResult() { var result = 1; var r = TryResult <int> .Succeed(result); Assert.AreEqual(result, r.Result); }
public async Task <TryResult <string> > FacebookLogin() { var result = await facebookLoginService.Login(); if (!result.OperationSucceeded) { if (result.Result?.LoginState == SocialLoginStateEnum.Canceled) { return(TryResult.Create(false, Translator.GetText("FacebookLoginCanceled"))); } if (result.Result?.LoginState == SocialLoginStateEnum.Failed) { return(TryResult.Create(false, result.Result?.ErrorString)); } } var loginInfo = new LoginInfo { Fb = new LoginInfo.Types.FacebookInfo { Token = result.Result.Token } }; var loginResult = await _client.loginAsync(loginInfo, new CallOptions()); if (loginResult?.Error != null) { return(TryResult.Create(false, loginResult?.Error?.Message)); } this.timelessTokenService.AuthorizationToken = loginResult.AuthToken; return(TryResult.Create(true, string.Empty)); }
public void CastFromTuple_WhenSuccess_SetsSuccessAndIgnoresError() { TryResult r = (true, "err"); Assert.IsTrue(r.Success); Assert.IsNull(r.ErrorMessage); }
public ApplicationServer() { Check("IsCentralLibrary") .AsExpensive <bool>(Check_IsCentralLibrary); Check("UID_ParentApplicationServer") .AsExpensive <string>(Check_UidParentApplicationServer); CanEdit("UID_ParentApplicationServer", "UID_ApplicationServerRedirect") .From("IsCentralLibrary") .As((bool isCentralLibrary) => !isCentralLibrary) .ClearValueOnFalse(); CanEdit("UseAlwaysLimit", "OnLineLimit") .From("UID_ApplicationServerRedirect") .As((string s) => string.IsNullOrEmpty(s)) .ClearValueOnFalse(); CanEdit("UseShadowFolder") .From("UID_ApplicationServerRedirect", "OnLineLimit") .As((string s, int limit) => string.IsNullOrEmpty(s) && limit == 0) .ClearValueOnFalse(); PreventLoops("UID_ParentApplicationServer"); Value("UseShadowFolder") .From("OnLineLimit") .As((int onLineLimit) => TryResult.FromResult(onLineLimit > 0, true)); }
private static TryResult <TValue> TryGetValue(ArneTreeNode <TKey, TValue> node, TKey key) { while (true) { if (node == null) { return(tryGetFailResult); } var compare = node.Value.CompareTo(key); if (compare > 0) { node = node.Left; } else if (compare < 0) { node = node.Right; } else { return(TryResult <TValue> .CreateSuccess(node.Value)); } } }
public void AddResult(int response_time, TryResult result) { if (avg_responsetime == 0) { //this is just the first try of this word avg_responsetime = response_time; } else { //not the first try - calculate average avg_responsetime += response_time; avg_responsetime = avg_responsetime / 2; } switch (result) { case TryResult.bad: this.bad_tries++; break; case TryResult.good: this.good_tries++; break; default: break; } }
public async Task ThenTryAsync_WhenTryFailed_ReturnsOriginalError() { var t = TryResult.Fail("err"); var t2 = await t.ThenTryAsync(async() => TryResult.Succeed()); Assert.AreEqual(t, t2); }
public void ThenTry_WhenTryFailed_ReturnsOriginalError() { TryResult t = "err"; var t2 = t.ThenTry(() => TryResult.Succeed()); Assert.AreEqual(t, t2); }
public void ThenTryTInTOut_WhenTryFailed_ReturnsOriginalError() { TryResult <int> t = "err"; var t2 = t.ThenTry <int, int>(r => 1); Assert.AreEqual(t.Result, t2.Result); }
public void ThenTIn_WhenTryFailed_ReturnsOriginalError() { TryResult <int> t = "err"; var t2 = t.Then(() => { }); Assert.AreEqual(t, t2); }
public void ThenTInTOut_WhenTryFailed_ReturnsOriginalError() { TryResult <int> t = "err"; var t2 = t.Then(r => 1); Assert.AreEqual(t.ErrorMessage, t2.ErrorMessage); }
public void ThenTryTIn_WhenTrySucceededAndExecutorSucceeds_ReturnsResultOfOriginalTry() { TryResult <int> t = 1; var tr = t.ThenTry(r => TryResult.Succeed()); Assert.AreEqual(t, tr); }
public async Task ThenAsyncTOut_WhenTryFailed_ReturnsOriginalError() { TryResult t = "err"; var t2 = await t.ThenAsync(async() => 1); Assert.AreEqual(t.ErrorMessage, t2.ErrorMessage); }
public TryResult MoveTo(string sourceFileName, string destinationFolderPath) { var tryResult = new TryResult(); var fileName = Path.GetFileName(sourceFileName); tryResult.Try(() => File.Move(sourceFileName, $"{destinationFolderPath}\\{fileName}")); return(tryResult); }
public void CastFromTuple_WhenFail_SetsError() { var err = "err"; TryResult r = (false, err); Assert.IsFalse(r.Success); Assert.AreEqual("err", r.ErrorMessage); }
public void CastFromString_SetsAsFailWithError() { var err = "err"; TryResult r = err; Assert.IsFalse(r.Success); Assert.AreEqual("err", r.ErrorMessage); }
public void CastToTuple_WhenFail_SetsSuccessAndError() { var r = TryResult.Fail("err"); (bool, string)o = r; Assert.AreEqual(r.Success, o.Item1); Assert.AreEqual(r.ErrorMessage, o.Item2); }
public void Deconstruct_WhenFail_Deconstructs() { var r = TryResult.Fail("err"); var(success, errMsg) = r; Assert.AreEqual(r.Success, success); Assert.AreEqual(r.ErrorMessage, errMsg); }
public void ToString_WhenFail_ContainsError() { var err = "argnull"; var r = TryResult.Fail(err); var s = r.ToString(); Assert.IsTrue(s.Contains(err)); }
/// <summary> /// Tries to gets the content of the request as string. /// </summary> /// <returns> /// An instance of <see cref="TryResult{T}"/> which encapsulates result of the operation. /// <see cref="TryResult{T}.Success"/> contains <c>true</c> if operation was successful, <c>false</c> otherwise. /// <see cref="TryResult{T}.Result"/> contains valid object if operation was successful, <c>null</c> otherwise. /// </returns> public TryResult<String> TryGetContentAsString() { if (contentAsStringResult.HasValue) { return contentAsStringResult.Value; } using (var memoryStream = new MemoryStream(Content)) { // Get input stream var inputStream = GetInputStream(memoryStream, ContentCompression); // Initialize a new instance of the StreamReader class for the input stream using (var streamReader = new StreamReader(inputStream, Encoding.UTF8)) { try { // Read all characters from the start to the end of the stream var result = streamReader.ReadToEnd(); contentAsStringResult = TryResult<String>.CreateSuccess(result); } catch (InvalidOperationException) { contentAsStringResult = getContentAsStringFailResult; } } } return contentAsStringResult.Value; }