Example #1
0
        public void Test5_1_Collections()
        {
            var m1 = new MegaType(
                new[] { 0, 1 },
                new FSharpMap <string, int>(new List <Tuple <string, int> > {
                new Tuple <string, int>("key", 10)
            }),
                new FSharpSet <int>(new[] { 1 }),
                new FSharpList <FSharpOption <int> >(new FSharpOption <int>(22), FSharpList <FSharpOption <int> > .Empty),
                new[] { new[] { 0, 1 } },
                new int[, ] {
            }
                );

            Assert.True(MapModule.ContainsKey("key", m1.Maps));

            var newSet = SetModule.Add(2, m1.Sets); //does not mutate set

            Assert.NotEqual(newSet, m1.Sets);

            if (OptionModule.IsSome(ListModule.Head(m1.Lists)))
            {
                Assert.Equal(22, ListModule.Head(m1.Lists).Value);
            }

            //Lists are linked lists, immutable and have structural equality

            Assert.Equal(m1.Arrays, m1.ArrayofArrays[0]); //Structural equality

            m1.Arrays[0] = 1;
            Assert.Equal(m1.Arrays, new[] { 1, 1 }); //Arrays are mutable
        }
Example #2
0
        public async Task <ActionResult> Register(RegisterPatientCommand command)
        {
            command.VisitId = new VisitId(Guid.NewGuid());

            var errors = Visit.validateCommand(command);

            if (errors.Any())
            {
                foreach (var error in errors)
                {
                    var field        = OptionModule.IsSome(error.Item1) ? error.Item1.Value : "";
                    var errorMessage = error.Item2;
                    ModelState.AddModelError(field, errorMessage);
                }
                return(View());
            }
            else
            {
                FSharpChoice <FSharpList <Tuple <string, object, EmergencyEventMetadata> >, NonEmptyList <CommandFailure> > result = await _system.RunCommand(command);

                if (result.IsChoice1Of2)
                {
                    return(View("Success"));
                }
                else
                {
                    var errorResult = ((FSharpChoice <FSharpList <Tuple <string, object, EmergencyEventMetadata> >, NonEmptyList <CommandFailure> > .Choice2Of2)result).Item;
                    foreach (var error in errorResult)
                    {
                        var commandError = error as CommandFailure.CommandError;
                        if (commandError != null)
                        {
                            ModelState.AddModelError("", commandError.Item);
                        }

                        var commandExn = error as CommandFailure.CommandException;
                        if (commandExn != null)
                        {
                            ModelState.AddModelError("", commandExn.Item1 + ": " + commandExn.Item2);
                        }
                        var fieldError = error as CommandFailure.CommandFieldError;
                        if (fieldError != null)
                        {
                            ModelState.AddModelError(fieldError.Item1, fieldError.Item2);
                        }
                    }
                    return(View());
                }
            }
        }
Example #3
0
        public bool TryGetValue(TKey key, out TValue value)
        {
            var res = innerMap.TryFind(key);

            if (OptionModule.IsSome(res))
            {
                value = res.Value;
                return(true);
            }
            else
            {
                value = default(TValue);
                return(false);
            }
        }
        public IActionResult Index(int year)
        {
            var worldCupFsharpOption = _worldCupRepository.FindByYear(YearModule.create(year));

            if (OptionModule.IsSome(worldCupFsharpOption)) //you'll get access to Option, List, etc module options as well
            {
                var worldCupFsharp = worldCupFsharpOption.Value;

                var worldCupVm = new WorldCupVm
                {
                    Year   = YearModule.value(worldCupFsharp.Year),
                    Host   = WorldCupHostModule.value(worldCupFsharp.Host),
                    Winner = CountryModule.value(worldCupFsharp.Winner)
                };

                return(Content(JsonConvert.SerializeObject(worldCupVm), "application/json"));
            }

            return(NotFound());
        }
Example #5
0
        public void Test4_1_Options()
        {
            var b1 = new PollResult(FSharpOption <int> .Some(1), FSharpOption <int> .None);

            var b2 = new PollResult(FSharpOption <int> .Some(1), FSharpOption <int> .Some(1));

            //The OptionModule is a static class providing static methods for interacting with Option types

            if (OptionModule.IsSome(b1.Yes))   //guarding access
            {
                Assert.Equal(1, b1.Yes.Value); //safe to access Value
            }

            var n1 = OptionModule.ToNullable(b1.No); //convert to more idiomatic C#

            Assert.Null(n1);
            var n2 = OptionModule.ToNullable(b1.Yes);

            Assert.Equal(1, n2);

            Assert.NotEqual(b1, b2);
        }
Example #6
0
        public async Task DoUpdateAsync()
        {
            if (IsDisposed)
            {
                return;
            }

            var buffer = _currentSnapshot;
            var path   = _document.FilePath;

            // replace with user token
            var token    = _cts.Token;
            var instance = await FsLintVsPackage.Instance.WithCancellation(token);

            // this acts as a throttle
            await Task.Delay(200, token);

            if (Project == null)
            {
                await instance.JoinableTaskFactory.SwitchToMainThreadAsync();

                var project = instance.Dte.Solution.FindProjectItem(path)?.ContainingProject;

                if (project == null)
                {
                    return;
                }

                if (instance.SolutionService.GetProjectOfUniqueName(project.UniqueName, out var vsHierarchy) != VSConstants.S_OK)
                {
                    return;
                }

                if (instance.SolutionService.GetGuidOfProject(vsHierarchy, out var guid) != VSConstants.S_OK)
                {
                    return;
                }

                Project = new LintProjectInfo(project.Name, guid, vsHierarchy);
            }

            await Task.Yield();

            var connectionString = SqlAnalyzer.tryFindConnectionString(path);

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                return;
            }



            var source     = _currentSnapshot.GetText();
            var sourceText = SourceText.ofString(source);

            var getProjectOptions = _provider.CheckerInstance.GetProjectOptionsFromScript(
                filename: path,
                source: sourceText,
                assumeDotNetFramework: false,
                useSdkRefs: true,
                useFsiAuxLib: true,
                previewEnabled: true,
                otherFlags: new string[] { "--targetprofile:netstandard" },
                loadedTimeStamp: FSharpOption <DateTime> .None,
                extraProjectInfo: FSharpOption <object> .None,
                optionsStamp: FSharpOption <long> .None,
                userOpName: FSharpOption <string> .None,
                sdkDirOverride: FSharpOption <string> .None
                );

            var(options, errors) = await FSharpAsync.StartAsTask(getProjectOptions, null, token);

            if (errors.Any())
            {
                return;
            }

            var performParseAndCheck = _provider.CheckerInstance.ParseAndCheckFileInProject(
                filename: path,
                fileVersion: 1,
                sourceText: sourceText,
                options: options,
                userOpName: FSharpOption <string> .None
                );

            var(parseResults, checkAnswer) = await FSharpAsync.StartAsTask(performParseAndCheck, null, token);

            if (parseResults.ParseHadErrors || checkAnswer.IsAborted)
            {
                return;
            }

            var checkResults = SqlAnalyzer.checkAnswerResult(checkAnswer).Value;

            var context = new SqlAnalyzerContext(
                fileName: path,
                content: source.Split('\n'),
                parseTree: parseResults.ParseTree.Value,
                symbols: SqlAnalyzer.getSymbols(checkResults)
                );

            var operationBlocks = SyntacticAnalysis.findSqlOperations(context);
            var loadedSchema    = SqlAnalysis.databaseSchema(connectionString);

            var errorMessages = new List <Message>();

            if (loadedSchema.IsError)
            {
                foreach (var operation in operationBlocks)
                {
                    var containsSkipAnalysis = operation.blocks.Any(block => block.IsSkipAnalysis);
                    foreach (var block in operation.blocks)
                    {
                        var blockRange = block.Range();
                        if ((block.IsQuery || block.IsTransaction) && OptionModule.IsSome(blockRange) && !containsSkipAnalysis)
                        {
                            var internalError = (loadedSchema.ErrorValue ?? "").Replace("3D000:", "").Replace("28P01:", "");
                            var fullError     = $"Error occured while trying to connect to the database using the configured connection string in NPGSQL_FSHARP in order to perform static analysis:{internalError}";
                            var errorMessage  = new Message(
                                type: "Error",
                                message: fullError,
                                code: "SQL101",
                                severity: Severity.Warning,
                                range: blockRange.Value,
                                fixes: Microsoft.FSharp.Collections.FSharpList <Fix> .Empty
                                );

                            errorMessages.Add(errorMessage);
                        }
                    }
                }
            }
            else
            {
                var databaseSchema = loadedSchema.ResultValue;
                foreach (var operation in operationBlocks)
                {
                    foreach (var analysisOutput in SqlAnalysis.analyzeOperation(operation, connectionString, databaseSchema))
                    {
                        errorMessages.Add(analysisOutput);
                    }
                }
            }

            var oldLintingErrors = this.Factory.CurrentSnapshot;
            var newLintErrors    = new LintingErrorsSnapshot(_document, oldLintingErrors.VersionNumber + 1);

            foreach (var error in errorMessages)
            {
                var span = RangeToSpan(error.Range, buffer);
                newLintErrors.Errors.Add(new LintError(span, error, Project));
            }

            await instance.JoinableTaskFactory.SwitchToMainThreadAsync();

            if (token.IsCancellationRequested)
            {
                return;
            }

            UpdateLintingErrors(newLintErrors);
        }