/// <summary>
        /// Evaluates the embedded script parsing out {{ C# Expression }}
        /// blocks and evaluating the expressions and embedding the string
        /// output into the result string.
        ///
        ///
        /// </summary>
        /// <param name="code">The code to execute
        /// <param name="model">Optional model data accessible in Expressions as `Model`</param>
        /// <returns></returns>
        public async Task <bool> EvaluateScriptAsync(string code, CommanderAddinModel model = null)
        {
            ScriptInstance = CreateScriptObject();

            string oldPath = Environment.CurrentDirectory;

            code = "public async Task<string> ExecuteScript(CommanderAddinModel Model)\n" +
                   "{\n" +
                   code + "\n" +
                   "return \"ok\";\n" +
                   "}";

            string res = await ScriptInstance.ExecuteMethodAsync <string>(code, "ExecuteScript", model);

            Directory.SetCurrentDirectory(oldPath);


            if (ScriptInstance.Error)
            {
                // fix error offsets so they match just the script code
                FixupLineNumbersAndErrors(ScriptInstance);
                ErrorMessage = ScriptInstance.ErrorMessage;
            }

            return(!ScriptInstance.Error);
        }
        public override async Task OnApplicationStart()
        {
            AddinModel = new CommanderAddinModel {
                AppModel           = Model,
                AddinConfiguration = CommanderAddinConfiguration.Current,
                Addin = this
            };

            await base.OnApplicationStart();

            Id = "Commander";

            // by passing in the add in you automatically
            // hook up OnExecute/OnExecuteConfiguration/OnCanExecute
            var menuItem = new AddInMenuItem(this)
            {
                Caption          = "Commander C# Script Automation",
                FontawesomeIcon  = FontAwesomeIcon.Terminal,
                KeyboardShortcut = CommanderAddinConfiguration.Current.KeyboardShortcut
            };

            try
            {
                menuItem.IconImageSource = new ImageSourceConverter()
                                           .ConvertFromString("pack://application:,,,/CommanderAddin;component/icon_22.png") as ImageSource;
            }
            catch { }


            // if you don't want to display config or main menu item clear handler
            //menuItem.ExecuteConfiguration = null;
            // Must add the menu to the collection to display menu and toolbar items
            MenuItems.Add(menuItem);
        }
        public CommanderWindow(CommanderAddin addin)
        {
            InitializeComponent();
            mmApp.SetThemeWindowOverride(this);

            Model             = addin.AddinModel;
            Model.AddinWindow = this;


            if (Model.AddinConfiguration.Commands == null || Model.AddinConfiguration.Commands.Count < 1)
            {
                Model.AddinConfiguration.Commands = new ObservableCollection <CommanderCommand>();
                Model.AddinConfiguration.Commands.Add(
                    new CommanderCommand
                {
                    Name        = "Console Test",
                    CommandText = "for(int x = 1;  x < 5; x++) {\n    Console.WriteLine(\"Hello World \" + x.ToString());\n}\n\n// Demonstrate async functionality\nusing (var client = new WebClient())\n{\n    var uri = new Uri(\"https://albumviewer.west-wind.com/api/album/37\");\n    var json = await client.DownloadStringTaskAsync(uri);\n    Console.WriteLine($\"\\n{json}\");\n}",
                });

                Model.AddinConfiguration.Commands.Add(
                    new CommanderCommand
                {
                    Name        = "Open in VsCode",
                    CommandText =
                        "var docFile = Model.ActiveDocument.Filename;\nif (string.IsNullOrEmpty(docFile))\n\treturn null;\n\nModel.Window.SaveFile();\n\nvar exe = @\"C:\\Program Files\\Microsoft VS Code\\Code.exe\";\nexe = Environment.ExpandEnvironmentVariables(exe);\n\nProcess pi = null;\ntry {\n\tvar lineNo = await Model.ActiveEditor.GetLineNumber();\n\tpi = Process.Start(exe,\"-g \\\"\" + docFile + $\":{lineNo + 1}\\\"\");\n}\ncatch(Exception ex) {\n\tModel.Window.ShowStatusError(\"Couldn't open editor: \" + ex.Message);\n\treturn null;\n}\n\nif (pi != null)\n    Model.Window.ShowStatus($\"VS Code  started with: {docFile}\",5000);\nelse\n    Model.Window.ShowStatusError(\"Failed to start VS Code.\");\n",
                    KeyboardShortcut = "Alt-Shift-V"
                });
            }
            else
            {
                Model.AddinConfiguration.Commands =
                    new ObservableCollection <CommanderCommand>(Model.AddinConfiguration.Commands.OrderBy(snip => snip.Name));
                if (Model.AddinConfiguration.Commands.Count > 0)
                {
                    Model.ActiveCommand = Model.AddinConfiguration.Commands[0];
                }
            }

            Loaded   += CommandsWindow_Loaded;
            Unloaded += CommanderWindow_Unloaded;

            WebBrowserCommand.Visibility = Visibility.Hidden;

            DataContext = Model;
        }
예제 #4
0
        public CommanderWindow(CommanderAddin addin)
        {
            InitializeComponent();
            mmApp.SetThemeWindowOverride(this);

            Model             = addin.AddinModel;
            Model.AddinWindow = this;


            if (Model.AddinConfiguration.Commands == null || Model.AddinConfiguration.Commands.Count < 1)
            {
                Model.AddinConfiguration.Commands = new ObservableCollection <CommanderCommand>();
                Model.AddinConfiguration.Commands.Add(
                    new CommanderCommand
                {
                    Name        = "Console Test",
                    CommandText = @"
for(int x = 1;  x < 10; x++) {
    Console.WriteLine(""Hello World "" + x.ToString());
}"
                });
                Model.AddinConfiguration.Commands.Add(
                    new CommanderCommand
                {
                    Name             = "Git Commit Active Document",
                    KeyboardShortcut = "Alt-Shift-G",
                    CommandText      = @"
// ASSSUMES: Git is in your system path. Otherwise add path here
var gitExe = ""git.exe"";

var doc = Model.ActiveDocument.Filename;
var docFile = Path.GetFileName(doc);
var docPath = Path.GetDirectoryName(doc);

Directory.SetCurrentDirectory(docPath);

Console.WriteLine(""Staging "" + docFile);
int result = Model.ExecuteProcess(gitExe, ""add --force -- \"""" + docFile + ""\"""");
Console.WriteLine(result == 0 ? ""Success"" : ""Nothing to stage. Exit Code: "" + result);

Console.WriteLine(""Committing..."");
result = Model.ExecuteProcess(gitExe, ""commit -m \""Updating documentation for "" + docFile + ""\"""");
Console.WriteLine(result == 0 ? ""Success"" : ""Nothing to commit. Exit Code: "" + result);

if (result != 0)
return null;

Console.WriteLine(""Pushing..."");
result = Model.ExecuteProcess(gitExe, ""push --porcelain --progress --recurse-submodules=check origin refs/heads/master:refs/heads/master"");
Console.WriteLine(result == 0 ? ""Success"" : ""Nothing to push. Exit Code: "" + result);
"
                });
            }
            else
            {
                Model.AddinConfiguration.Commands =
                    new ObservableCollection <CommanderCommand>(Model.AddinConfiguration.Commands.OrderBy(snip => snip.Name));
                if (Model.AddinConfiguration.Commands.Count > 0)
                {
                    Model.ActiveCommand = Model.AddinConfiguration.Commands[0];
                }
            }

            Loaded   += CommandsWindow_Loaded;
            Unloaded += CommanderWindow_Unloaded;

            WebBrowserCommand.Visibility = Visibility.Hidden;

            DataContext = Model;
        }