public PrismicContext(prismic.Api.Api api, FSharpOption<string> maybeRef, FSharpOption<string> maybeAccessToken, prismic.Api.DocumentLinkResolver linkResolver)
 {
     this.api = api;
     this.maybeRef = maybeRef;
     this.maybeAccessToken = maybeAccessToken;
     this.linkResolver = linkResolver;
 }
Beispiel #2
0
		private static async Task DoRequest()
		{
			Console.WriteLine(ApiQuery);
			var storage = new FSharpOption<IStorageAsync>(new Storage.JsonFileStorage(@"..\..\client_secrets.json", @"..\..\stored_credentials.json"));
			var httpclient = OAuth2Client.HttpClientFactory.WithOAuth2("query-api-1.0", storage, null, null);

			var response = await httpclient.PostAsync(ApiEndpoint, new StringContent(ApiQuery));
			if (response.StatusCode != HttpStatusCode.OK)
			{
				var errorBody = await response.Content.ReadAsStringAsync();
				throw new Exception("Request failed:\n" + errorBody);
			}

			var jsonBody = await response.Content.ReadAsStringAsync();
			Console.WriteLine(jsonBody);
			var resultSets = JArray.Parse(jsonBody);
			var results =
				from item in resultSets[0]
				select new {Name = item["Name"], Estimate = item["Estimate"]}
				;

			foreach (var item in results)
			{
				Console.WriteLine("{0} {1}", item.Name, item.Estimate);
			}
		}
 public static IEnumerable <T> AsEnumerable <T>(this FSharpOption <T> o) =>
 o.IsSome() ? Enumerable.Repeat(o.Value, 1) : Enumerable.Empty <T>();
 /// <summary>
 /// Convert a LanguageExt OptionUnsafe into an F# Option
 /// </summary>
 public static FSharpOption <T> ToFSharp <T>(this OptionUnsafe <T> option) =>
 matchUnsafe(option,
             Some: v => FSharpOption <T> .Some(v),
             None: () => FSharpOption <T> .None);
 /// <summary>
 /// Convert a F# Option into a LanguageExt Option
 /// </summary>
 public static Option <T> fs <T>(FSharpOption <T> fsOption) =>
 FSharpOption <T> .get_IsSome(fsOption)
         ? Some(fsOption.Value)
         : None;
Beispiel #6
0
        int IOleCommandTarget.Exec(ref Guid commandGroup, uint commandId, uint commandExecOpt, IntPtr variantIn, IntPtr variantOut)
        {
            try
            {
                EditCommand editCommand;
                if (TryConvert(commandGroup, commandId, variantIn, out editCommand))
                {
                    if (editCommand.IsUndo)
                    {
                        _buffer.UndoRedoOperations.Undo(1);
                        return NativeMethods.S_OK;
                    }
                    else if (editCommand.IsRedo)
                    {
                        _buffer.UndoRedoOperations.Redo(1);
                        return NativeMethods.S_OK;
                    }
                    else if (editCommand.HasKeyInput)
                    {
                        var keyInput = editCommand.KeyInput;

                        // Swallow the input if it's been flagged by a previous QueryStatus
                        if (SwallowIfNextExecMatches.IsSome() && SwallowIfNextExecMatches.Value == keyInput)
                        {
                            return NativeMethods.S_OK;
                        }

                        var commandData = new OleCommandData(commandId, commandExecOpt, variantIn, variantOut);
                        if (TryExec(ref commandGroup, ref commandData, keyInput))
                        {
                            return NativeMethods.S_OK;
                        }
                    }
                }
            }
            finally
            {
                SwallowIfNextExecMatches = FSharpOption<KeyInput>.None;
            }

            return _nextTarget.Exec(commandGroup, commandId, commandExecOpt, variantIn, variantOut);
        }
 private static string EntryToString( FSharpOption<Entry> entry )
 {
     return FSharpOption<Entry>.get_IsNone( entry )
         ? string.Empty
         : entry.Value.Value.ToString( CultureInfo.InvariantCulture );
 }
Beispiel #8
0
        public Task <IDotNetCompilation> GetFunctionCompilationAsync(FunctionMetadata functionMetadata)
        {
            // First use the C# compiler to resolve references, to get consistency with the C# Azure Functions programming model
            // Add the #r statements from the .fsx file to the resolver source
            string scriptSource          = GetFunctionSource(functionMetadata);
            var    resolverSourceBuilder = new StringBuilder();

            using (StringReader sr = new StringReader(scriptSource))
            {
                string line;

                while ((line = sr.ReadLine()) != null)
                {
                    if (_hashRRegex.IsMatch(line))
                    {
                        resolverSourceBuilder.AppendLine(line);
                    }
                }
            }

            resolverSourceBuilder.AppendLine("using System;");
            var resolverSource = resolverSourceBuilder.ToString();

            Script <object> script = CodeAnalysis.CSharp.Scripting.CSharpScript.Create(resolverSource, options: _metadataResolver.CreateScriptOptions(), assemblyLoader: AssemblyLoader.Value);

            var compiler = new SimpleSourceCodeServices(msbuildEnabled: FSharpOption <bool> .Some(false));

            FSharpErrorInfo[]       errors         = null;
            FSharpOption <Assembly> assemblyOption = null;

            string scriptPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            Directory.CreateDirectory(scriptPath);

            string scriptFilePath = Path.Combine(scriptPath, Path.GetFileName(functionMetadata.ScriptFile));

            var assemblyName     = FunctionAssemblyLoader.GetAssemblyNameFromMetadata(functionMetadata, Guid.NewGuid().ToString());
            var assemblyFileName = Path.Combine(scriptPath, assemblyName + ".dll");
            var pdbName          = Path.ChangeExtension(assemblyFileName, PlatformHelper.IsMono ? "dll.mdb" : "pdb");

            try
            {
                var scriptFileBuilder = new StringBuilder();

                // Write an adjusted version of the script file, prefixing some 'open' declarations
                foreach (string import in script.Options.Imports)
                {
                    scriptFileBuilder.AppendLine("open " + import);
                }

                // Suppress undesirable warnings
                scriptFileBuilder.AppendLine("#nowarn \"988\"");

                // Set the line to match the original script
                scriptFileBuilder.AppendLine("# 0 @\"" + functionMetadata.ScriptFile + "\"");

                // Add our original script
                scriptFileBuilder.AppendLine(scriptSource);

                File.WriteAllText(scriptFilePath, scriptFileBuilder.ToString());

                var otherFlags = new List <string>();

                otherFlags.Add("fsc.exe");

                // The --noframework option is used because we will shortly add references to mscorlib and FSharp.Core
                // as dictated by the C# reference resolver, and F# doesn't like getting multiple references to those.
                otherFlags.Add("--noframework");

                var references = script.GetCompilation().References
                                 .Where(m => !(m is UnresolvedMetadataReference))
                                 .Select(m => "-r:" + m.Display)
                                 .Distinct(new FileNameEqualityComparer());

                // Add the references as reported by the metadata resolver.
                otherFlags.AddRange(references);

                if (_optimizationLevel == OptimizationLevel.Debug)
                {
                    otherFlags.Add("--optimize-");
                    otherFlags.Add("--debug+");
                    otherFlags.Add("--tailcalls-");
                }

                if (PlatformHelper.IsMono)
                {
                    var monoDir    = Path.GetDirectoryName(typeof(string).Assembly.Location);
                    var facadesDir = Path.Combine(monoDir, "Facades");
                    otherFlags.Add("--lib:" + facadesDir);
                }

                // If we have a private assembly folder, make sure the compiler uses it to resolve dependencies
                string privateAssembliesFolder = Path.Combine(Path.GetDirectoryName(functionMetadata.ScriptFile), DotNetConstants.PrivateAssembliesFolderName);
                if (Directory.Exists(privateAssembliesFolder))
                {
                    otherFlags.Add("--lib:" + Path.Combine(Path.GetDirectoryName(functionMetadata.ScriptFile), DotNetConstants.PrivateAssembliesFolderName));
                }

                otherFlags.Add("--out:" + assemblyFileName);

                // Get the #load closure
                FSharpChecker checker = FSharpChecker.Create(null, null, null, msbuildEnabled: FSharpOption <bool> .Some(false));
                var           loadFileOptionsAsync = checker.GetProjectOptionsFromScript(functionMetadata.ScriptFile, scriptSource, null, null, null);
                var           loadFileOptions      = FSharp.Control.FSharpAsync.RunSynchronously(loadFileOptionsAsync, null, null);
                foreach (var loadedFileName in loadFileOptions.ProjectFileNames)
                {
                    if (Path.GetFileName(loadedFileName) != Path.GetFileName(functionMetadata.ScriptFile))
                    {
                        otherFlags.Add(loadedFileName);
                    }
                }

                // Add the (adjusted) script file itself
                otherFlags.Add(scriptFilePath);

                // Compile the script to a static assembly
                var result = compiler.Compile(otherFlags.ToArray());
                errors = result.Item1;
                var code = result.Item2;

                if (code == 0)
                {
                    var    assemblyBytes = File.ReadAllBytes(assemblyFileName);
                    byte[] pdbBytes      = null;
                    if (File.Exists(pdbName))
                    {
                        pdbBytes = File.ReadAllBytes(pdbName);
                    }
                    var assembly = Assembly.Load(assemblyBytes, pdbBytes);
                    assemblyOption = FSharpOption <Assembly> .Some(assembly);
                }
                else
                {
                    string message = $"F# compilation failed with arguments: {string.Join(" ", otherFlags)}";
                    _traceWriter.Verbose(message);
                    _logger?.LogDebug(message);
                }
            }
            finally
            {
                DeleteDirectoryAsync(scriptPath, recursive: true)
                .ContinueWith(
                    t => t.Exception.Handle(e =>
                {
                    string message = $"Unable to delete F# compilation file: {e.ToString()}";
                    _traceWriter.Warning(message);
                    _logger?.LogWarning(message);
                    return(true);
                }), TaskContinuationOptions.OnlyOnFaulted);
            }

            return(Task.FromResult <IDotNetCompilation>(new FSharpCompilation(errors, assemblyOption)));
        }
 public static bool IsNone <T>(this FSharpOption <T> option)
 {
     return(FSharpOption <T> .get_IsNone(option));
 }
Beispiel #10
0
        public int UpdateTerrainCubes(TerrainModel terrain, FSharpOption<TerrainModel> old)
        {
            HashSet<ClientConnection> newClients;
            int newCube = WorldModel.GetCubeKey(terrain.Position);

            if (!CubeClients.TryGetValue(newCube, out newClients))
                newClients = new HashSet<ClientConnection>();

            if (old != null)
            {
                int oldCube = WorldModel.GetCubeKey(old.Value.Position);
                HashSet<ClientConnection> oldClients;
                if (!CubeClients.TryGetValue(oldCube, out oldClients))
                    oldClients = new HashSet<ClientConnection>();
                if (oldCube != newCube)
                    foreach (var c in oldClients.Except(newClients))
                        c.Drop(terrain);
            }

            foreach (var c in newClients)
                c.Send(terrain);

            return newCube;
        }
Beispiel #11
0
        public int UpdateEntityCubes(EntityModel entity, FSharpOption<EntityModel> old)
        {
            int newCube = WorldModel.GetCubeKey(entity.Position);

            // update client cubes if the entity was possessed
            ClientConnection client;
            if (Possession.TryGetValue(entity.Id, out client)) { 
                var newCubes = new HashSet<int>(WorldModel.GetNearbyCubeKeys(newCube));

                HashSet<int> oldCubes;
                HashSet<ClientConnection> clients;
                IEnumerable<int> add;
                if (ClientCubes.TryGetValue(client, out oldCubes))
                {
                    foreach (var cube in oldCubes.Except(newCubes))
                    {
                        if (CubeClients.TryGetValue(cube, out clients))
                        {
                            clients.Remove(client);
                            if (clients.Count == 0)
                                CubeClients.Remove(cube);
                        }
                    }
                    add = newCubes.Except(oldCubes);
                }
                else
                    add = newCubes;

                foreach (var cube in add)
                    if (CubeClients.TryGetValue(cube, out clients))
                        clients.Add(client);
                    else
                        CubeClients.Add(cube, new HashSet<ClientConnection> { client });

                ClientCubes[client] = newCubes;
            }

            // notify all clients subscribed to the relevant cubes
            HashSet<ClientConnection> newClients;
            if (!CubeClients.TryGetValue(newCube, out newClients))
                newClients = new HashSet<ClientConnection>();

            if (old != null)
            {
                int oldCube = WorldModel.GetCubeKey(old.Value.Position);
                HashSet<ClientConnection> oldClients;
                if (!CubeClients.TryGetValue(oldCube, out oldClients))
                    oldClients = new HashSet<ClientConnection>();
                if (oldCube != newCube)
                    foreach (var c in oldClients.Except(newClients))
                        c.Drop(entity);
            }

            foreach (var c in newClients.Where(x => x != client))
                c.Send(entity);

            return newCube;
        }
Beispiel #12
0
        public void Start()
        {
            Double distanceTheta = 1.0, shavingTheta = 0.99, shavingAlpha = 0.2;
            int phevLearningWindow = 40, nDays = 10;

            Int32.TryParse(textBoxPhevLearning.Text, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out phevLearningWindow);
            Int32.TryParse(textBoxDays.Text, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out nDays);
            Double.TryParse(textBoxDistanceTheta.Text, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out distanceTheta);
            Double.TryParse(textBoxShavingAlpha.Text, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out shavingAlpha);
            Double.TryParse(textBoxShavingTheta.Text, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out shavingTheta);

            button1.Enabled = false;

            FSharpOption<Sim.Method> method = null;
            FSharpOption<Sim.Contribution> contr = null;
            FSharpOption<Sim.Scheduler> scheduler = null;

            started = DateTime.Now;

            updateLog("-------------------------------------");
            String dayah = "", mech = "", phev = "";
            switch (comboBox1.SelectedItem.ToString())
            {
                case "Peak-shaving":
                    dayah = String.Format("Centralized (peak-shaving): alpha={0}, theta={1}", shavingAlpha, shavingTheta);
                    method = new FSharpOption<Sim.Method>(Sim.Method.Shaving);
                    break;
                case "Distance-rule":
                    dayah = String.Format("Centralized (distance-rule): theta={0}", distanceTheta);
                    method = new FSharpOption<Sim.Method>(Sim.Method.Distance);
                    break;
                case "Superposition":
                    method = new FSharpOption<Sim.Method>(Sim.Method.Superposition);
                    break;
                case "Random":
                    dayah = (String.Format("Decentralized (Random)"));
                    method = new FSharpOption<Sim.Method>(Sim.Method.Random);
                    break;
                case "Mixed":
                    dayah = (String.Format("Decentralized (Mixed)"));
                    method = new FSharpOption<Sim.Method>(Sim.Method.Mixed);
                    break;
                case "None":
                    method = FSharpOption<Sim.Method>.None;
                    break;
            }
            updateLog(String.Format("Dayahead:\t {0}", dayah));
            switch (comboBox2.SelectedItem.ToString())
            {
                case "Proactive":
                    mech = "Proactive";
                    scheduler = new FSharpOption<Sim.Scheduler>(Sim.Scheduler.Proactive);
                    break;
                case "Reactive":
                    mech = "Reactive";
                    scheduler = new FSharpOption<Sim.Scheduler>(Sim.Scheduler.Reactive);
                    break;
                case "Random":
                    mech = "Random";
                    scheduler = new FSharpOption<Sim.Scheduler>(Sim.Scheduler.Random);
                    break;
                case "Mixed":
                    mech = "Mixed";
                    scheduler = new FSharpOption<Sim.Scheduler>(Sim.Scheduler.Mixed);
                    break;
                case "None":
                    mech = "None";
                    scheduler = FSharpOption<Sim.Scheduler>.None;
                    break;
            }
            updateLog(String.Format("Mechanism:\t {0}", mech));

            switch (comboBox3.SelectedItem.ToString())
            {
                case "Expected":
                    phev = "Expected";
                    contr = new FSharpOption<Sim.Contribution>(Sim.Contribution.Expected);
                    break;
                case "Simulated":
                    phev = "Simulated";
                    contr = new FSharpOption<Sim.Contribution>(Sim.Contribution.Simulated);
                    break;
                case "None":
                    phev = "None";
                    contr = FSharpOption<Sim.Contribution>.None;
                    break;
            }
            updateLog(String.Format("Contribution:\t {0}", phev));
            updateLog(String.Format("Window (PHEV):\t {0}", phevLearningWindow));
            updateLog(String.Format("Days:\t\t {0}", nDays));
            updateLog("-------------------------------------");
            tSim.PhevWindow = phevLearningWindow;
            tSim.Scheduler = scheduler;
            tSim.DistanceTheta = distanceTheta;
            tSim.ShavingAlpha = shavingAlpha;
            tSim.ShavingTheta = shavingTheta;
            tSim.Method = method;
            tSim.Contribution = contr;
            tSim.Days = nDays;
            progressBar1.Minimum = 0;

            BackgroundWorker bgWorker;
            bgWorker = new BackgroundWorker();
            bgWorker.DoWork += new DoWorkEventHandler(Simulation_Start);
            bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(Simulation_Completed);
            bgWorker.RunWorkerAsync(tSim);
        }
 public Task<prismic.Api.Api> Get(FSharpOption<string> accessToken)
 {
     return prismic.extensions.Api.Get (accessToken, this.apiUrl, cache, this.logger);
 }
 public BackRefEventArgs(FSharpOption<ICSharpLiteralExpression> br)
 {
     BackRef = br;
 }
 public static bool IsSome <T>(this FSharpOption <T> o) => FSharpOption <T> .get_IsSome(o);
 public static FSharpOption <TR> Bind <T, TR>(this FSharpOption <T> option, Func <T, FSharpOption <TR> > f)
 {
     return(option.IsNone() ? FSharpOption <TR> .None : f(option.Value));
 }
 public FSharpCompilation(FSharpErrorInfo[] errors, FSharpOption<Assembly> assemblyOption)
 {
     _errors = errors;
     _assemblyOption = assemblyOption;
 }
Beispiel #18
0
 internal static MotionData CreateMotionData(
     Motion motion,
     int count)
 {
     return(CreateMotionData(motion, new MotionArgument(MotionContext.AfterOperator, FSharpOption.Create(count), FSharpOption <int> .None)));
 }
Beispiel #19
0
 private static string BuildXUnit2Args(FSharpOption<Tuple<string, string>> includeTrait, FSharpOption<Tuple<string, string>> excludeTrait)
 {
     var parameters = new XUnit2Helper.XUnit2Params("", "", XUnit2Helper.ParallelOption.None, 0, false, false,
         true, false, false,null, TimeSpan.FromMinutes(5), UnitTestCommon.TestRunnerErrorLevel.Error, includeTrait, excludeTrait, false, false, true, "");
     return XUnit2Helper.buildXUnit2Args(parameters, "test.dll");
 }
Beispiel #20
0
 /// <summary>
 /// Converts <see cref="FSharpOption{T}"/> to <see cref="Nullable"/>.
 /// </summary>
 private static T?AsNullable <T>(this FSharpOption <T> opt) where T : struct
 {
     return(FSharpOption <T> .get_IsNone(opt) ? new T?() : opt.Value);
 }
Beispiel #21
0
        public static Dictionary<AST.Address, string> StoreOutputs(AST.Address[] outputs, DAG dag)
        {
            // output dict
            var d = new Dictionary<AST.Address, string>();

            // partition all of the output addresses by their worksheet
            var addr_groups = outputs.GroupBy(addr => dag.getCOMRefForAddress(addr).WorksheetName);

            // for each worksheet, do an array read of the formulas
            foreach (IEnumerable<AST.Address> ws_fns in addr_groups)
            {
                // get worksheet used range
                var fstcr = dag.getCOMRefForAddress(ws_fns.First());
                var rng = fstcr.Worksheet.UsedRange;

                // get used range dimensions
                var left = rng.Column;
                var right = rng.Columns.Count + left - 1;
                var top = rng.Row;
                var bottom = rng.Rows.Count + top - 1;

                // get names
                var wsname = new FSharpOption<string>(fstcr.WorksheetName);
                var wbname = new FSharpOption<string>(fstcr.WorkbookName);
                var path = fstcr.Path;

                // sometimes the used range is a range
                if (left != right || top != bottom)
                {
                    // y is the first index
                    // x is the second index
                    object[,] data = rng.Value2;    // fast array read

                    var x_del = left - 1;
                    var y_del = top - 1;

                    foreach (AST.Address addr in ws_fns)
                    {
                        // construct address in formulas array
                        var x = addr.X - x_del;
                        var y = addr.Y - y_del;

                        // get string
                        String s = System.Convert.ToString(data[y, x]);
                        if (String.IsNullOrWhiteSpace(s))
                        {
                            d.Add(addr, "");
                        }
                        else
                        {
                            d.Add(addr, s);
                        }
                    }
                }
                // and other times it is a single cell
                else
                {
                    // construct the appropriate AST.Address
                    AST.Address addr = AST.Address.NewFromR1C1(top, left, wsname, wbname, path);

                    // make certain that it is actually a string
                    String s = System.Convert.ToString(rng.Value2);

                    // add to dictionary, as appropriate
                    if (String.IsNullOrWhiteSpace(s))
                    {
                        d.Add(addr, "");
                    }
                    else
                    {
                        d.Add(addr, s);
                    }
                }
            }

            return d;
        }
Beispiel #22
0
 protected void RaiseActiveTextViewChanged(FSharpOption<ITextView> oldTextView, FSharpOption<ITextView> newTextView)
 {
     if (_activeTextViewChanged != null)
     {
         var args = new TextViewChangedEventArgs(oldTextView, newTextView);
         _activeTextViewChanged(this, args);
     }
 }
Beispiel #23
0
        int IOleCommandTarget.Exec(ref Guid commandGroup, uint commandId, uint commandExecOpt, IntPtr variantIn, IntPtr variantOut)
        {
            try
            {
                EditCommand editCommand;
                if (TryConvert(commandGroup, commandId, variantIn, out editCommand))
                {
                    if (editCommand.IsUndo)
                    {
                        // The user hit the undo button.  Don't attempt to map anything here and instead just
                        // run a single Vim undo operation
                        _buffer.UndoRedoOperations.Undo(1);
                        return NativeMethods.S_OK;
                    }
                    else if (editCommand.IsRedo)
                    {
                        // The user hit the redo button.  Don't attempt to map anything here and instead just
                        // run a single Vim redo operation
                        _buffer.UndoRedoOperations.Redo(1);
                        return NativeMethods.S_OK;
                    }
                    else if (editCommand.HasKeyInput)
                    {
                        var keyInput = editCommand.KeyInput;

                        // Swallow the input if it's been flagged by a previous QueryStatus
                        if (SwallowIfNextExecMatches.IsSome() && SwallowIfNextExecMatches.Value == keyInput)
                        {
                            return NativeMethods.S_OK;
                        }

                        // Try and process the command with the IVimBuffer
                        var commandData = new OleCommandData(commandId, commandExecOpt, variantIn, variantOut);
                        if (TryProcessWithBuffer(ref commandGroup, ref commandData, keyInput))
                        {
                            return NativeMethods.S_OK;
                        }
                    }
                }
            }
            finally
            {
                SwallowIfNextExecMatches = FSharpOption<KeyInput>.None;
            }

            return _nextTarget.Exec(commandGroup, commandId, commandExecOpt, variantIn, variantOut);
        }
Beispiel #24
0
 protected void AssertPosition(int lineNumber, int column, FSharpOption<VirtualSnapshotPoint> option)
 {
     Assert.True(option.IsSome());
     var line = VirtualSnapshotPointUtil.GetPoint(option.value).GetColumn();
     Assert.Equal(lineNumber, line.LineNumber);
     Assert.Equal(column, line.Column);
 }
Beispiel #25
0
        /// <summary>
        /// With Resharper installed we need to special certain keys like Escape.  They need to 
        /// process it in order for them to dismiss their custom intellisense but their processing 
        /// will swallow the event and not propagate it to us.  So handle, return and account 
        /// for the double stroke in exec
        /// </summary>
        private CommandAction? QueryStatusInResharper(KeyInput keyInput)
        {
            CommandAction? action = null;
            if (_buffer.ModeKind == ModeKind.Insert && keyInput == KeyInputUtil.EscapeKey)
            {
                // Have to special case Escape here for insert mode.  R# is typically ahead of us on the IOleCommandTarget
                // chain.  If a completion window is open and we wait for Exec to run R# will be ahead of us and run
                // their Exec call.  This will lead to them closing the completion window and not calling back into
                // our exec leaving us in insert mode.
                action = CommandAction.Enable;
            }
            else if (_buffer.ModeKind == ModeKind.ExternalEdit && keyInput == KeyInputUtil.EscapeKey)
            {
                // Have to special case Escape here for external edit mode because we want escape to get us back to
                // normal mode
                action = CommandAction.Enable;
            }
            else if (_adapter.InDebugMode && (keyInput == KeyInputUtil.EnterKey || keyInput.Key == VimKey.Back))
            {
                // In debug mode R# will intercept Enter and Back
                action = CommandAction.Enable;
            }
            else if (keyInput == KeyInputUtil.EnterKey && _buffer.ModeKind != ModeKind.Insert && _buffer.ModeKind != ModeKind.Replace)
            {
                // R# will intercept the Enter key when we are in the middle of an XML doc comment presumable
                // to do some custom formatting.  If we're not insert mode we need to handle that here and
                // suppress the command to keep them from running it
                action = CommandAction.Disable;
            }

            // Only process the KeyInput if we are enabling the value.  When the value is Enabled
            // we return Enabled from QueryStatus and Visual Studio will push the KeyInput back
            // through the event chain where either of the following will happen
            //
            //  1. R# will handle the KeyInput
            //  2. R# will not handle it, it will get back to us and we will ignore it
            //
            // If the command is disabled though it will not go through IOleCommandTarget and instead will end
            // up in the KeyProcessor code which will handle the value
            if (action.HasValue && action.Value == CommandAction.Enable && _buffer.Process(keyInput).IsAnyHandled)
            {
                SwallowIfNextExecMatches = FSharpOption.Create(keyInput);
            }

            return action;
        }
 /// <summary>
 /// Convert a LanguageExt Option into an F# Option
 /// </summary>
 public static FSharpOption <T> ToFSharp <T>(this Option <T> option) =>
 option.IsNone
         ? FSharpOption <T> .None
         : match(option,
                 Some: v => FSharpOption <T> .Some(v),
                 None: () => failwith <FSharpOption <T> >("returns null, so can't use the None branch"));
 public void SerializationTests_FSharp_IntOption_Some()
 {
     RoundtripSerializationTest(FSharpOption <int> .Some(10));
 }
 public static bool IsSomeValue <T>(this FSharpOption <T> o, T value) => o.IsSome() && o.Value.Equals(value);
Beispiel #29
0
 public abstract FSharpOption <ListItem> NavigateToListItem(ListKind listKind, NavigationKind navigationKind, FSharpOption <int> argument, bool hasBang);
 public static T GetOr <T>(this FSharpOption <T> o, T ifNone) =>
 o.IsSome() ? o.Value : ifNone;
Beispiel #31
0
 public Microsoft.FSharp.Core.FSharpOption <ITextView> GetFocusedTextView()
 {
     return(FSharpOption.CreateForReference(FocusedTextView));
 }
 public static T ValueOrDefault <T>(this FSharpOption <T> option, T defaultValue)
 {
     return(option.IsNone() ? defaultValue : option.Value);
 }
Beispiel #33
0
            public Instance Create()
            {
                var completed = WebSharper.UI.Templating.Runtime.Server.Handler.CompleteHoles(key, holes, new Tuple <string, WebSharper.UI.Templating.Runtime.Server.ValTy>[] { Tuple.Create("name", WebSharper.UI.Templating.Runtime.Server.ValTy.String) });
                var doc       = WebSharper.UI.Templating.Runtime.Server.Runtime.GetOrLoadTemplate("index", FSharpOption <string> .Some("main"), FSharpOption <string> .Some("index.html"), "\r\n        <ul ws-hole=\"ListContainer\">\r\n            <li ws-template=\"ListItem\">${Name}</li>\r\n        </ul>\r\n        <div>\r\n            <input ws-var=\"Name\" placeholder=\"Name\">\r\n            <button ws-onclick=\"Add\">Add</button>\r\n            <div>You are about to add: ${Name}</div>\r\n        </div>\r\n    ", completed.Item1, FSharpOption <string> .Some("index"), ServerLoad.WhenChanged, new Tuple <string, FSharpOption <string>, string>[] {  }, false);

                instance = new Instance(completed.Item2, doc);
                return(instance);
            }
 public static FSharpOption <TR> Map <T, TR>(this FSharpOption <T> option, Func <T, TR> f)
 {
     return(option.IsNone() ? FSharpOption <TR> .None : FSharpOption <TR> .Some(f(option.Value)));
 }
Beispiel #35
0
        public Instance Create()
        {
            var completed = WebSharper.UI.Templating.Runtime.Server.Handler.CompleteHoles(key, holes, new Tuple <string, WebSharper.UI.Templating.Runtime.Server.ValTy>[] {  });
            var doc       = WebSharper.UI.Templating.Runtime.Server.Runtime.GetOrLoadTemplate("index", null, FSharpOption <string> .Some("index.html"), "<!DOCTYPE html>\r\n<html lang=\"en\">\r\n<head>\r\n    <title>$safeprojectname$</title>\r\n    <meta charset=\"utf-8\">\r\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"Content/$safeprojectname$.css\">\r\n    <style>\r\n        /* Don't show the not-yet-loaded templates */\r\n        [ws-template], [ws-children-template] {\r\n            display: none;\r\n        }\r\n    </style>\r\n    <script type=\"text/javascript\" src=\"Content/$safeprojectname$.head.js\"></script>\r\n</head>\r\n<body>\r\n    <h1>My list of unique people</h1>\r\n    <div id=\"main\" ws-children-template=\"Main\">\r\n        <ul ws-hole=\"ListContainer\">\r\n            <li ws-template=\"ListItem\">${Name}</li>\r\n        </ul>\r\n        <div>\r\n            <input ws-var=\"Name\" placeholder=\"Name\">\r\n            <button ws-onclick=\"Add\">Add</button>\r\n            <div>You are about to add: ${Name}</div>\r\n        </div>\r\n    </div>\r\n    <script type=\"text/javascript\" src=\"Content/$safeprojectname$.min.js\"></script>\r\n</body>\r\n</html>\r\n", completed.Item1, FSharpOption <string> .Some("index"), ServerLoad.WhenChanged, new Tuple <string, FSharpOption <string>, string>[] {  }, false);

            instance = new Instance(completed.Item2, doc);
            return(instance);
        }
Beispiel #36
0
        internal static Tuple <IIndex <a>, VectorConstruction> restrictToRowIndex <a>(Lookup lookup, IIndex <a> restriction, IIndex <a> sourceIndex, VectorConstruction vector)
        {
            if ((((lookup != Lookup.Exact ? 0 : (restriction.IsOrdered ? 1 : 0)) == 0 ? 0 : (sourceIndex.IsOrdered ? 1 : 0)) == 0 ? 0 : (!restriction.IsEmpty ? 1 : 0)) == 0)
            {
                return(new Tuple <IIndex <a>, VectorConstruction>(sourceIndex, vector));
            }
            Tuple <a, a> keyRange = restriction.KeyRange;
            a            a1       = keyRange.Item1;
            a            a2       = keyRange.Item2;

            return(sourceIndex.Builder.GetRange <a>(new Tuple <IIndex <a>, VectorConstruction>(sourceIndex, vector), new Tuple <FSharpOption <Tuple <a, BoundaryBehavior> >, FSharpOption <Tuple <a, BoundaryBehavior> > >(FSharpOption <Tuple <a, BoundaryBehavior> > .Some(new Tuple <a, BoundaryBehavior>(a1, BoundaryBehavior.get_Inclusive())), FSharpOption <Tuple <a, BoundaryBehavior> > .Some(new Tuple <a, BoundaryBehavior>(a2, BoundaryBehavior.get_Inclusive())))));
        }
Beispiel #37
0
            public Instance Create()
            {
                var completed = WebSharper.UI.Templating.Runtime.Server.Handler.CompleteHoles(key, holes, new Tuple <string, WebSharper.UI.Templating.Runtime.Server.ValTy>[] {  });
                var doc       = WebSharper.UI.Templating.Runtime.Server.Runtime.GetOrLoadTemplate("index", FSharpOption <string> .Some("listitem"), FSharpOption <string> .Some("index.html"), "<li>${Name}</li>", completed.Item1, FSharpOption <string> .Some("index"), ServerLoad.WhenChanged, new Tuple <string, FSharpOption <string>, string>[] {  }, true);

                instance = new Instance(completed.Item2, doc);
                return(instance);
            }
Beispiel #38
0
 internal static BindData <T> CreateBindData <T>(Func <KeyInput, BindResult <T> > func = null, KeyRemapMode remapMode = null)
 {
     func = func ?? (x => BindResult <T> .Cancelled);
     return(new BindData <T>(FSharpOption.CreateForReference(remapMode), func.ToFSharpFunc()));
 }
Beispiel #39
0
        public FSharpOption <ITextView> GetFocusedTextView()
        {
            var doc = IdeServices.DocumentManager.ActiveDocument;

            return(FSharpOption.CreateForReference(TextViewFromDocument(doc)));
        }
Beispiel #40
0
 public static FSharpOption <T> Some <T>(T obj)
 {
     return(FSharpOption <T> .Some(obj));
 }
Beispiel #41
0
 public FSharpOption <ITextView> LoadFileIntoNewWindow(string filePath, FSharpOption <int> line, FSharpOption <int> column)
 {
     if (File.Exists(filePath))
     {
         var document = IdeApp.Workbench.OpenDocument(filePath, null, line.SomeOrDefault(0), column.SomeOrDefault(0)).Result;
         var textView = TextViewFromDocument(document);
         return(FSharpOption.CreateForReference(textView));
     }
     return(FSharpOption <ITextView> .None);
 }
Beispiel #42
0
 public static FSharpOption <T> ToFsOption <T>(Option <T> option) =>
 option.Match(() => FSharpOption <T> .None,
              v => FSharpOption <T> .Some(v));
Beispiel #43
0
        public FSharpOption <ListItem> NavigateToListItem(ListKind listKind, NavigationKind navigationKind, FSharpOption <int> argumentOption, bool hasBang)
        {
            if (listKind == ListKind.Error)
            {
                var errors = IdeServices.TaskService.Errors;
                if (errors.Count > 0)
                {
                    var argument = argumentOption.IsSome() ? new int?(argumentOption.Value) : null;

                    var currentIndex = errors.CurrentLocationTask == null ? -1 : errors.IndexOf(errors.CurrentLocationTask);
                    var index        = GetListItemIndex(navigationKind, argument, currentIndex, errors.Count);

                    if (index.HasValue)
                    {
                        var errorItem = errors.ElementAt(index.Value);
                        errors.CurrentLocationTask = errorItem;
                        errorItem.SelectInPad();
                        errorItem.JumpToPosition();

                        // Item number is one-based.
                        var listItem = new ListItem(index.Value + 1, errors.Count, errorItem.Message);
                        return(FSharpOption.CreateForReference(listItem));
                    }
                }
            }
            return(FSharpOption <ListItem> .None);
        }
Beispiel #44
0
 public void Create(bool haveRealTransaction = true)
 {
     _factory          = new MockRepository(MockBehavior.Strict);
     _editorOperations = _factory.Create <IEditorOperations>();
     if (haveRealTransaction)
     {
         _realTransaction = _factory.Create <ITextUndoTransaction>();
         _transactionRaw  = new UndoTransaction(FSharpOption.Create(_realTransaction.Object), FSharpOption.Create(_editorOperations.Object));
     }
     else
     {
         _transactionRaw = new UndoTransaction(FSharpOption <ITextUndoTransaction> .None, FSharpOption <IEditorOperations> .None);
     }
     _transaction = _transactionRaw;
 }
Beispiel #45
0
        /// <summary>
        /// With Resharper installed we need to special certain keys like Escape.  They need to
        /// process it in order for them to dismiss their custom intellisense but their processing
        /// will swallow the event and not propagate it to us.  So handle, return and account
        /// for the double stroke in exec
        /// </summary>
        private CommandStatus?QueryStatusInResharper(KeyInput keyInput)
        {
            CommandStatus?status          = null;
            var           passToResharper = true;

            if (_buffer.ModeKind.IsAnyInsert() && keyInput == KeyInputUtil.EscapeKey)
            {
                // Have to special case Escape here for insert mode.  R# is typically ahead of us on the IOleCommandTarget
                // chain.  If a completion window is open and we wait for Exec to run R# will be ahead of us and run
                // their Exec call.  This will lead to them closing the completion window and not calling back into
                // our exec leaving us in insert mode.
                status = CommandStatus.Enable;
            }
            else if (_buffer.ModeKind == ModeKind.ExternalEdit && keyInput == KeyInputUtil.EscapeKey)
            {
                // Have to special case Escape here for external edit mode because we want escape to get us back to
                // normal mode.  However we do want this key to make it to R# as well since they may need to dismiss
                // intellisense
                status = CommandStatus.Enable;
            }
            else if ((keyInput.Key == VimKey.Back || keyInput == KeyInputUtil.EnterKey) && _buffer.ModeKind != ModeKind.Insert)
            {
                // R# special cases both the Back and Enter command in various scenarios
                //
                //  - Enter is special cased in XML doc comments presumably to do custom formatting
                //  - Enter is supressed during debugging in Exec.  Presumably this is done to avoid the annoying
                //    "Invalid ENC Edit" dialog during debugging.
                //  - Back is special cased to delete matched parens in Exec.
                //
                // In all of these scenarios if the Enter or Back key is registered as a valid Vim
                // command we want to process it as such and prevent R# from seeing the command.  If
                // R# is allowed to see the command they will process it often resulting in double
                // actions
                status          = CommandStatus.Enable;
                passToResharper = false;
            }

            // Only process the KeyInput if we are enabling the value.  When the value is Enabled
            // we return Enabled from QueryStatus and Visual Studio will push the KeyInput back
            // through the event chain where either of the following will happen
            //
            //  1. R# will handle the KeyInput
            //  2. R# will not handle it, it will come back to use in Exec and we will ignore it
            //     because we mark it as silently handled
            if (status.HasValue && status.Value == CommandStatus.Enable && _buffer.Process(keyInput).IsAnyHandled)
            {
                // We've broken the rules a bit by handling the command in QueryStatus and we need
                // to silently handle this command if it comes back to us again either through
                // Exec or through the VsKeyProcessor
                _bufferCoordinator.DiscardedKeyInput = FSharpOption.Create(keyInput);

                // If we need to cooperate with R# to handle this command go ahead and pass it on
                // to them.  Else mark it as Disabled.
                //
                // Marking it as Disabled will cause the QueryStatus call to fail.  This means the
                // KeyInput will be routed to the KeyProcessor chain for the ITextView eventually
                // making it to our VsKeyProcessor.  That component respects the SilentlyHandled
                // statu of KeyInput and will siently handle it
                status = passToResharper ? CommandStatus.Enable : CommandStatus.Disable;
            }

            return(status);
        }
Beispiel #46
0
 private static string BuildXUnitArgs(FSharpOption<Tuple<string, string>> includeTrait, FSharpOption<Tuple<string, string>> excludeTrait)
 {
     return XUnitHelper.buildXUnitArgs(new XUnitHelper.XUnitParams("","",false,false,false,"",false,false,TimeSpan.MinValue,"",UnitTestCommon.TestRunnerErrorLevel.Error,includeTrait,excludeTrait), "test.dll");
 }
Beispiel #47
0
 private static FSharpOption <MotionResult> CreateMotionResultSome()
 {
     return(FSharpOption.Create(CreateMotionResult()));
 }
Beispiel #48
0
        /// <summary>
        /// With Resharper installed we need to special certain keys like Escape.  They need to 
        /// process it in order for them to dismiss their custom intellisense but their processing 
        /// will swallow the event and not propagate it to us.  So handle, return and account 
        /// for the double stroke in exec
        /// </summary>
        private CommandAction? QueryStatusInResharper(KeyInput keyInput)
        {
            CommandAction? action = null;
            if (_buffer.ModeKind == ModeKind.Insert && keyInput == KeyInputUtil.EscapeKey)
            {
                // Have to special case Escape here for insert mode.  R# is typically ahead of us on the IOleCommandTarget
                // chain.  If a completion window is open and we wait for Exec to run R# will be ahead of us and run
                // their Exec call.  This will lead to them closing the completion window and not calling back into
                // our exec leaving us in insert mode.
                action = CommandAction.Enable;
            }
            else if (_buffer.ModeKind == ModeKind.ExternalEdit && keyInput == KeyInputUtil.EscapeKey)
            {
                // Have to special case Escape here for external edit mode because we want escape to get us back to
                // normal mode
                action = CommandAction.Enable;
            }
            else if (_adapter.InDebugMode && (keyInput == KeyInputUtil.EnterKey || keyInput.Key == VimKey.Back))
            {
                // In debug mode R# will intercept Enter and Back
                action = CommandAction.Enable;
            }
            else if (keyInput == KeyInputUtil.EnterKey && _buffer.ModeKind != ModeKind.Insert && _buffer.ModeKind != ModeKind.Replace)
            {
                // R# will intercept the Enter key when we are in the middle of an XML doc comment presumable
                // to do some custom formatting.  If we're not insert mode we need to handle that here and
                // suppress the command to keep them from running it
                action = CommandAction.Disable;
            }

            if (action.HasValue && _buffer.Process(keyInput))
            {
                SwallowIfNextExecMatches = FSharpOption.Create(keyInput);
            }

            return action;
        }
Beispiel #49
0
 internal static Command CreateLongCommand(string name, Func<KeyInput, bool> func, FSharpOption<KeyRemapMode> keyRemapModeOption = null, CommandFlags flags = CommandFlags.None)
 {
     return CreateLongCommand(
         name,
         (x, y) =>
         {
             FSharpFunc<KeyInput, LongCommandResult> realFunc = null;
             Converter<KeyInput, LongCommandResult> func2 = ki =>
                 {
                     if (func(ki))
                     {
                         return LongCommandResult.NewFinished(CommandResult.NewCompleted(ModeSwitch.NoSwitch));
                     }
                     else
                     {
                         return LongCommandResult.NewNeedMoreInput(keyRemapModeOption, realFunc);
                     }
                 };
             realFunc = func2;
             return LongCommandResult.NewNeedMoreInput(keyRemapModeOption, realFunc);
         },
         flags);
 }