public void WhenErrorIsSet_ErrorSuppliedToFunction() { var valueOrError = ValueOrError.WithError("2"); var result = valueOrError.Match <string>().Value().Do(s => "v" + s).Error().Do(s => "e" + s).Result(); AreEqual("e2", result); }
public void WhenError_SimpleErrorDoWithExpressionSupported() { var valueOrError = ValueOrError.WithError("1"); var result = valueOrError.Match <int>().Value().Do(1).Error().Do(2).Result(); AreEqual(2, result); }
public void WhenErrorIsSetAndNoErrorMatch_ElseResultIsReturned() { var valueOrError = ValueOrError.WithError("2"); var result = valueOrError.Match <int>().Value().Do(x => 0).Else(x => 3).Result(); AreEqual(3, result); }
public void WhenSome_SomeOfDoWithExpressionSupported() { var valueOrError = ValueOrError.WithValue("1"); var result = valueOrError.Match <int>().Value().Of("1").Do(1).Value().Do(2).Error().Do(3).Result(); AreEqual(1, result); }
public void InvokeMatchedOrDefaultAction(ValueOrError <T1> inputArgument) { if (inputArgument.IsError) { if (_errorActions.Count != 0) { _errorActions[0](inputArgument.Error); } else { _matchNotFoundAction(); } } else { var action = _testsAndActions .Slinq() .FirstOrNone((matcher, param) => matcher.Item1(param.Value), inputArgument); if (action.isSome) { action.value.Item2(inputArgument.Value); } else if (_onValueDefaultAction.isSome) { _onValueDefaultAction.value(inputArgument.Value); } else { _matchNotFoundAction(); } } }
private ValueOrError <string> FetchNextCommand(StreamReader sr) { var delayTask = Task.Delay(TimeSpan.FromSeconds(1)); string nextCommand = null; while (IsNullOrComment(nextCommand) && !delayTask.IsCompleted) { nextCommand = sr.ReadLine(); if (nextCommand != null && nextCommand.StartsWith("//")) { logger.Log(LogLevel.Info, nextCommand); } } if (nextCommand != null) { return(ValueOrError.FromValue(nextCommand)); } return(ValueOrError.FromError <string>("Error: timeout of reading next command reached")); bool IsNullOrComment(string value) { return(value == null || value.StartsWith("//")); } }
public void Subscribe(ISingleSubscriber <T> s) { SingleDisposable sd = new SingleDisposable(this, s); s.OnSubscribe(sd); if (Add(sd)) { if (sd.IsDisposed()) { Remove(sd); } if (Volatile.Read(ref once) == 0) { if (Interlocked.CompareExchange(ref once, 1, 0) == 0) { source.Subscribe(this); } } } else { ValueOrError r = Volatile.Read(ref result); if (r.IsError()) { s.OnError(r.error); } else { s.OnSuccess(r.value); } } }
private ValueOrError <IConceptInfo> ParseMembers(ITokenReader tokenReader, IConceptInfo lastConcept, bool readingAReference) { IConceptInfo conceptInfo = (IConceptInfo)Activator.CreateInstance(ConceptInfoType); bool firstMember = true; bool lastPropertyWasInlineParent = false; bool lastConceptUsed = false; var listOfMembers = readingAReference ? Members.Where(m => m.IsKey) : Members.Where(m => m.IsParsable); foreach (ConceptMember member in listOfMembers) { var valueOrError = ReadMemberValue(member, tokenReader, lastConcept, firstMember, ref lastPropertyWasInlineParent, ref lastConceptUsed, readingAReference); if (valueOrError.IsError) { return(ValueOrError <IConceptInfo> .CreateError(string.Format(CultureInfo.InvariantCulture, "Cannot read the value of {0} in {1}. {2}", member.Name, ConceptInfoType.Name, valueOrError.Error))); } member.SetMemberValue(conceptInfo, valueOrError.Value); firstMember = false; } if (!lastConceptUsed && lastConcept != null) { return(ValueOrError <IConceptInfo> .CreateError(string.Format( "This concept cannot be enclosed within {0}. Trying to read {1}.", lastConcept.GetType().Name, ConceptInfoType.Name))); } return(ValueOrError <IConceptInfo> .CreateValue(conceptInfo)); }
void Test() { ValueOrError <float> logOrError = ValueOrError <float> .SafeLogarithm(5); ValueOrError <ValueOrError <float> > logLogOrError = logOrError.ApplyFunction(ValueOrError <float> .SafeLogarithm); ValueOrError <float> flatternLogLogOrError = logOrError.ApplySpecialFunction(ValueOrError <float> .SafeLogarithm); }
public ValueOrError <string> CreateUser(string data) { var credentials = JsonConvert.DeserializeObject <Credentials>(data); if (PlayerPrefs.HasKey(credentials.UserId)) { credentials.Status = Status.LogInInUse; return(ValueOrError <string> .CreateFromValue(JsonConvert.SerializeObject(credentials))); } credentials.Status = Status.Ok; var json = JsonConvert.SerializeObject(credentials); var playerData = new PlayerData { password = credentials.Password }; var dataJson = JsonConvert.SerializeObject(playerData); PlayerPrefs.SetString(credentials.UserId, dataJson); AddUserId(credentials.UserId); return(ValueOrError <string> .CreateFromValue(json)); }
public ValueOrError <string> GetResource(ResourceType type, string id) { var json = PlayerPrefs.GetString(id); var playerData = JsonConvert.DeserializeObject <PlayerData>(json); var res = new Resource { Type = type }; switch (type) { case ResourceType.Food: res.Value = playerData.food; break; case ResourceType.Gold: res.Value = playerData.gold; break; case ResourceType.Metal: res.Value = playerData.metal; break; case ResourceType.Wood: res.Value = playerData.wood; break; default: return(ValueOrError <string> .CreateFromError("Invalid request")); } res.UserId = id; return(ValueOrError <string> .CreateFromValue(JsonConvert.SerializeObject(res))); }
public Task <ValueOrError <User> > RemoveUserToken(string token) { var us = from u in _users.Values where u.Tokens.Any(t => t == token) select u; var voe = us.SingleOrDefault().ToValueOrError(); if (!voe.HasValue) { return(Task.FromResult(ValueOrError.Null <User>())); } var user = voe.Value; user = user.RemoveToken(token); _users.SetItem(user.Name, user); foreach (var c in _clusters.Values.Where(c => c.HasUser(user.Name))) { _clusters.SetItem(c.Name, c.SetUser(user)); } return(Task.FromResult(new ValueOrError <User>(user))); }
public Task <ValueOrError <Cluster> > AddCluster(string name, bool fromBackend = false) { var cluster = Cluster.Create(name); _clusters.Add(cluster.Name, cluster); return(Task.FromResult(ValueOrError.Create(cluster))); }
internal ValueOrErrorResultMatcherWithElse(ValueOrErrorMatchFunctionSelector <T1, TResult> selector, DelegateFunc <T1, TResult> elseAction, ValueOrError <T1> value) { _selector = selector; _elseAction = elseAction; _value = value; }
/// <param name="allowSystemProperties">Allows path to end with a C# property that does not have a representation in the DSL model (ID property or the Guid property used for a Reference).</param> public static ValueOrError <PropertyInfo> GetPropertyByPath(DataStructureInfo source, string path, IDslModel existingConcepts, bool allowSystemProperties = true) { if (path.Contains(" ")) { return(ValueOrError.CreateError("The path contains a space character.")); } if (string.IsNullOrEmpty(path)) { return(ValueOrError.CreateError("The path is empty.")); } var propertyNames = path.Split('.'); var referenceNames = propertyNames.Take(propertyNames.Count() - 1).ToArray(); var lastPropertyName = propertyNames[propertyNames.Count() - 1]; ValueOrError <DataStructureInfo> selectedDataStructure = source; foreach (var referenceName in referenceNames) { selectedDataStructure = NavigateToNextDataStructure(selectedDataStructure.Value, referenceName, existingConcepts); if (selectedDataStructure.IsError) { return(ValueOrError.CreateError(selectedDataStructure.Error)); } } PropertyInfo selectedProperty = FindProperty(existingConcepts, selectedDataStructure.Value, lastPropertyName); if (allowSystemProperties && selectedProperty == null && lastPropertyName == "ID") { return new GuidPropertyInfo { DataStructure = selectedDataStructure.Value, Name = "ID" } } ; if (allowSystemProperties && selectedProperty == null && lastPropertyName.EndsWith("ID")) { string referenceName = lastPropertyName.Substring(0, lastPropertyName.Length - 2); var referencePrototype = new PropertyInfo { DataStructure = selectedDataStructure.Value, Name = referenceName }; if (existingConcepts.FindByKey(referencePrototype.GetKey()) != null) { return new GuidPropertyInfo { DataStructure = selectedDataStructure.Value, Name = lastPropertyName } } ; } if (selectedProperty == null) { return(ValueOrError.CreateError("There is no property '" + lastPropertyName + "' on " + selectedDataStructure.Value.GetUserDescription() + ".")); } return(selectedProperty); }
public void GetHashCodeTest() { var error = "They have their exits and their entrances, And one man in his time plays many parts"; var valueOrError = ValueOrError <bool, string> .FromError(error); Assert.Equal(error.GetHashCode(), valueOrError.GetHashCode()); }
public ValueOrError <string> PostResource(string resourceData) { var resource = JsonConvert.DeserializeObject <Resource>(resourceData); var json = PlayerPrefs.GetString(resource.UserId); var playerData = JsonConvert.DeserializeObject <PlayerData>(json); switch (resource.Type) { case ResourceType.Food: playerData.food = resource.Value; break; case ResourceType.Gold: playerData.gold = resource.Value; break; case ResourceType.Metal: playerData.metal = resource.Value; break; case ResourceType.Wood: playerData.wood = resource.Value; break; default: return(ValueOrError <string> .CreateFromError("Invalid request")); } PlayerPrefs.SetString(resource.UserId, JsonConvert.SerializeObject(playerData)); return(ValueOrError <string> .CreateFromValue(JsonConvert.SerializeObject(resource))); }
public ValueOrError <string> Login(string data) { var credentials = JsonConvert.DeserializeObject <Credentials>(data); if (!PlayerPrefs.HasKey(credentials.UserId)) { credentials.Status = Status.UnknownLogin; return(ValueOrError <string> .CreateFromValue(JsonConvert.SerializeObject(credentials))); } var usedDataJson = PlayerPrefs.GetString(credentials.UserId); var usedData = JsonConvert.DeserializeObject <PlayerData>(usedDataJson); if (credentials.Status == Status.LogOut) { logInUsers.Remove(credentials.UserId); credentials.Status = Status.Ok; return(ValueOrError <string> .CreateFromValue(JsonConvert.SerializeObject(credentials))); } var allowAccess = credentials.Password.Equals(usedData.password); credentials.Status = allowAccess ? Status.Ok : Status.IncorrectPassword; if (allowAccess) { logInUsers.Add(credentials.UserId); } return(ValueOrError <string> .CreateFromValue(JsonConvert.SerializeObject(credentials))); }
public DateTime?GetNextOccurrence(string scheduleSpec, DateTime baseTime) { int?year; ParseYearField(ref scheduleSpec, out year); ValueOrError <CrontabSchedule> sch = CrontabSchedule.TryParse(scheduleSpec); if (sch.IsError) { throw sch.Error; } DateTime endTime = DateTime.MaxValue; // If an year is specified, restrict the next occurrences to that specific year. if (year != null) { if (year.Value != baseTime.Year) { baseTime = new DateTime(year.Value, 1, 1, 0, 0, 0, baseTime.Kind); } endTime = new DateTime(year.Value, 12, 31, 23, 59, 0, baseTime.Kind); } DateTime nextTime = sch.Value.GetNextOccurrence(baseTime, endTime); if (nextTime == endTime) { return(null); } return(nextTime); }
public Option <ValueOrError <TResult> > DetermineResult(ValueOrError <T> value) { return(_predicatesAndFuncs .Slinq() .FirstOrNone((tuple, p) => tuple.Item1(p.Value), value) .Select((pair, p) => ValueOrError <TResult> .FromValue(pair.Item2(p.Value)), value)); }
public void WhenValueIsSet_ValueSuppliedToFunction() { var valueOrError = ValueOrError.WithValue("1"); var result = valueOrError.Match <string>().Value().Do(s => "v" + s).Error().Do(s => "e" + s).Result(); AreEqual("v1", result); }
private async Task <ValueOrError <TResponse> > SendRequestWithCustomParser <TParameters, TResponse>(TParameters parameters, string method, Func <string, TResponse> parseResponse) { var content = new StringContent(JsonSerializer.Serialize(parameters), Encoding.UTF8, "application/json"); var results = await HttpClient.PostAsync($"Resources/AspNetFormsAuth/Authentication/{method}", content); var responseContent = await results.Content.ReadAsStringAsync(); if (results.StatusCode == HttpStatusCode.OK) { return(ValueOrError <TResponse> .CreateValue(parseResponse(responseContent))); } else if (results.StatusCode == HttpStatusCode.BadRequest || results.StatusCode == HttpStatusCode.Unauthorized) { string errorMessage = ""; if (results.StatusCode == HttpStatusCode.BadRequest) { errorMessage = JsonSerializer.Deserialize <RhetosErrorResponse>(responseContent).UserMessage; } return(ValueOrError <TResponse> .CreateError($"({(int)results.StatusCode}) {errorMessage}")); } else { throw new Exception("Response from server: " + responseContent); } }
private void Start() { /* * Func<X, M<Y>> f = whatever; * Func<Y, M<Z>> g = whatever; * * M<X> mx = whatever; * M<Y> my = ApplySpecialFunction(mx, f); * * M<Z> mz1 = ApplySpecialFunction(my, g); * Func<X, M<Z>> h = ComposeSpecial(f, g); * M<Z> mz2 = ApplySpecialFunction(mx, h); */ var argOrError = ValueOrError <int> .FromValue(121); var logOrError = argOrError.ApplySpecialFunction(logFunction); var decimalLogOrErrorFromFunctionSequence = logOrError.ApplySpecialFunction(toDecimalFunction); var composedLogAndToDecimal = ComposeSpecial(logFunction, toDecimalFunction); var decimalLogOrErrorFromComposed = argOrError.ApplySpecialFunction(composedLogAndToDecimal); Debug.Log($"decimalLogOrErrorFromFunctionSequence {decimalLogOrErrorFromFunctionSequence.Value} = " + $"decimalLogOrErrorFromComposed={decimalLogOrErrorFromComposed.Value}"); }
public void GetHashCodeTest() { var value = "All the world's a stage, And all the men and women merely players"; var valueOrError = ValueOrError <string, bool> .FromValue(value); Assert.Equal(value.GetHashCode(), valueOrError.GetHashCode()); }
public Task <ValueOrError <User> > AddUser(string name, bool fromBackend = false) { var user = User.Create(name); _users.Add(user.Name, user); return(Task.FromResult(ValueOrError.Create(user))); }
public async Task <IDisposable> Run(ValueOrError <User> user, RunTargets targets) { if (user.Value.Tokens.Count() > 1) { return(Disposable.Empty); } var name = user.Value.Name; Func <Task <IEnumerable <Source> > > getUserSources = async() => await targets.VisibilityPersistor.GetUserSources(name); var frontend = targets.ErrorsInbox != null ? targets.ErrorsInbox.GetErrorsStream() : Observable.Empty <ErrorPayload>(); var backend = targets.BackendErrorsInbox != null ? targets.BackendErrorsInbox.GetErrorsStream() : Observable.Empty <ErrorPayload>(); var errors = from e in frontend.Merge(backend) from sources in getUserSources() from a in sources where e.SourceId == a.SourceId select e; return(errors.Subscribe(payload => targets.FrontendNotifier.Error(name, payload))); }
public ValueOrError <bool> MakeMove(string move) { if (move == "pass") { CurrentColor = CurrentColor.Opposite(); return(ValueOrError.FromValue <bool>(true)); } var position = parser.TryParse(move); if (!position.HasValue) { return(ValueOrError.FromError <bool>($"Wrong code: {move}")); } if (possibleMovesFinder.GetPossibleMoves(Field).Any(possibleMove => possibleMove.Color == CurrentColor && possibleMove.Position == position.Value)) { var result = Field.MakeMove(move, CurrentColor); if (result.HasValue) { CurrentColor = CurrentColor.Opposite(); } return(result); } return(ValueOrError.FromError <bool>($"Move {move} is impossible for {CurrentColor}")); }
public async Task <IDisposable> Run(ValueOrError <User> user, RunTargets targets) { var name = user.Value.Name; //Initial recap var initialRecap = await InitialRecap(name, targets.VisibilityPersistor, targets.ErrorsBacklogReader, (a, r) => new { Sources = a, Recap = r }); var rs = from r in initialRecap.ToSingleton().ToObservable() select new { Sources = r.Sources, Additions = r.Sources, Removals = Enumerable.Empty <Source>() }; //Deltas var clusterSources = from p in targets.VisibilityPublisher.GetClusterSourcesSequence() let sources = p.Target.Primary.Sources let deltas = p.Target.Secondary.ToSingleton() let target = p.Target.Secondary.SourceId from u in p.Target.Primary.Users where u.Name == name select new { Sources = sources, Additions = p.Type == DeltaType.Added ? deltas : Enumerable.Empty <Source>(), Removals = p.Type == DeltaType.Removed ? deltas : Enumerable.Empty <Source>() }; var userSources = from p in targets.VisibilityPublisher.GetClusterUsersSequence() let sources = p.Target.Primary.Sources where p.Target.Secondary.Name == name select new { Sources = sources, Additions = p.Type == DeltaType.Added ? sources : Enumerable.Empty <Source>(), Removals = p.Type == DeltaType.Removed ? sources : Enumerable.Empty <Source>() }; var mergedSources = clusterSources.Merge(userSources); //Stream return(rs.Concat(mergedSources).Subscribe(async payload => { var recap = await targets.ErrorsBacklogReader.GetSourcesRecap(payload.Sources); if (!recap.HasValue) { return; } targets.FrontendNotifier.Recap(name, recap.Value); targets.FrontendNotifier.UserSources(name, payload.Additions, payload.Removals); })); }
private async void ButtonLaunch_Click(object sender, RoutedEventArgs eventArg) { SoftwareModel soft = (SoftwareModel)DataGrid_SoftwareList.SelectedItem; if (soft == null) { return; } showLoading(); try { int timeout = int.Parse(TextBox_Timeout.Text); string path = soft.path; string args = TextBox_LaunchArgs.Text; var tasks = computers.Select(async(computer) => { var r = new ValueOrError <WMIExecutionResult, Exception>(); try { r.value = await Task.Run(async() => { // Install on the current computer return(await computer.installSoftware(path, new string[] { args }, timeout)); }); } catch (Exception e) { r.error = e; } return(r); }); var results = await Task.WhenAll(tasks); var reports = new List <WMIExecutionResult>(); foreach (var result in results) { if (result.hasValue()) { reports.Add(result.value); } else { errorHandler.addError(result.error); WarningImage.Visibility = Visibility.Visible; } } // Show reports var reporter = new ExecutionReportsWindow(reports); reporter.Left = this.Left + 50; reporter.Top = this.Top + 50; reporter.Show(); } catch (Exception e) { WarningImage.Visibility = Visibility.Visible; errorHandler.addError(e); } finally { hideLoading(); } }
public Task <ValueOrError <Source> > AddSource(string name, string description, bool fromBackend = false) { var source = Source.Create(name, description); _sources.Add(source.SourceId, source); return(Task.FromResult(ValueOrError.Create(source))); }
internal ValueOrErrorMatcher(ValueOrError valueOrError) { _valueOrError = valueOrError; _resultActions = new Dictionary<bool, Action> { {false, () => _errorActionSelector.InvokeMatchedActionUsingDefaultIfRequired(_valueOrError.Error)}, {true, () => _valueActionSelector.InvokeMatchedActionUsingDefaultIfRequired(_valueOrError.Value)} }; }
public static Option<int> IntParser(ValueOrError data) => data.Match<Option<int>>() .Value().Where(s => s.StartsWith("Int:")).Do(s => s.Substring(4).TryParseInt()) .Else(Option<int>.None()) .Result();
private static Union<string, string> CreateUnionFromValueOrError(ValueOrError valueOrError) => valueOrError.HasValue ? new Union<string, string>(valueOrError.Value, null, Variant.Case1) : new Union<string, string>(null, valueOrError.Error, Variant.Case2);