Ejemplo n.º 1
0
        public IActionResult Index()
        {
            if (HybridSupport.IsElectronActive)
            {
                Electron.IpcMain.On("select-directory", async(args) => {
                    var mainWindow = Electron.WindowManager.BrowserWindows.First();
                    var options    = new OpenDialogOptions
                    {
                        Properties = new OpenDialogProperty[] {
                            OpenDialogProperty.openFile
                        }
                    };


                    string[] files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);

                    string csv       = System.IO.File.ReadAllText(files[0]);
                    StringBuilder sb = new StringBuilder();
                    using (var p = ChoCSVReader.LoadText(csv)
                                   .WithFirstLineHeader()
                           )
                    {
                        using (var w = new ChoJSONWriter(sb))
                            w.Write(p);
                    }
                    string json = sb.ToString();
                    Electron.IpcMain.Send(mainWindow, "select-directory-reply", json);
                });
            }
            return(View());
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> SetBlobSpecialValue([FromBody] SetSpecialValueRequest request)
        {
            if (!SpecialValues.ContainsKey(request.Key))
            {
                SpecialValues.Add(request.Key, null);
            }

            var mainWindow = Electron.WindowManager.BrowserWindows.First();
            var options    = new OpenDialogOptions
            {
                Properties = new OpenDialogProperty[] {
                    OpenDialogProperty.openFile
                }
            };

            request.Value = (await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options)).FirstOrDefault();
            if (System.IO.File.Exists(request.Value))
            {
                SpecialValues[request.Key] = Convert.ToBase64String(System.IO.File.ReadAllBytes(request.Value));
                BroadcastValueChanged(request.Key);
                return(Json(true));
            }
            else
            {
                // Show dialog
                return(Json(false));
            }
        }
Ejemplo n.º 3
0
        /// <inheritdoc />
        public async Task ExportAsync()
        {
            var openDialogOptions = new OpenDialogOptions
            {
                Title      = Translator.Translate("Please choose the Export location"),
                Properties = new[] { OpenDialogProperty.openDirectory }
            };
            var exportPath =
                (await ElectronHelper.ShowOpenDialogAsync(ElectronHelper.GetBrowserWindow(), openDialogOptions)).FirstOrDefault();

            if (!string.IsNullOrWhiteSpace(exportPath))
            {
                ExportStatus = ExportStatus.Exporting;

                // this is really not nice, but otherwise,
                // the UI won't be refreshed and no status message is displayed.
                ElectronHelper.ReloadBrowserWindow();

                CurrentProject.ExportImages(exportPath, i => ElectronHelper.SetProgressBar(i));

                ExportStatus = ExportStatus.ExportSuccessful;
                ElectronHelper.SetProgressBar(-1); // remove progress bar

                // this is really not nice, but otherwise,
                // the UI won't be refreshed and no status message is displayed.
                ElectronHelper.ReloadBrowserWindow();
            }
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> ImportWorlds()
        {
            try
            {
                var mainWindow = Electron.WindowManager.BrowserWindows.First();
                var options    = new OpenDialogOptions
                {
                    Title   = "Install Datapack",
                    Filters = new FileFilter[]
                    {
                        new FileFilter {
                            Name       = "Zip Files",
                            Extensions = new string[] { "zip" }
                        }
                    },
                    Properties = new OpenDialogProperty[]
                    { OpenDialogProperty.openDirectory }
                };
                var res = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);

                var file = res[0];
                Startup.ImportWorlds(file);
                Startup.Save();
            }
            catch { }
            return(RedirectToAction(nameof(Index)));
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> AddDatapack(string id)
        {
            try
            {
                var world = Worlds.FirstOrDefault(x => x.Name == id);
                if (world == null || !Directory.Exists(world.Path + "/datapacks"))
                {
                    return(RedirectToAction(nameof(Index)));
                }
                var index = Worlds.IndexOf(world);
                Worlds.Remove(world);

                var mainWindow = Electron.WindowManager.BrowserWindows.First();
                var options    = new OpenDialogOptions
                {
                    Title   = "Install Datapack",
                    Filters = new FileFilter[]
                    {
                        new FileFilter {
                            Name       = "Zip Files",
                            Extensions = new string[] { "zip" }
                        }
                    }
                };
                var res = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);

                var file = res[0];
                await AddDatapack(world, file);

                Worlds.Insert(index, world);
                Startup.Save();
            }
            catch { }
            return(RedirectToAction(nameof(Index)));
        }
Ejemplo n.º 6
0
        public async Task <string[]> SelectDirectory([FromBody] SelectDirectoryDTO selectDirectoryDTO)
        {
            try
            {
                OpenDialogOptions options = new OpenDialogOptions
                {
                    Properties = new OpenDialogProperty[2]
                };

                if (selectDirectoryDTO.SelectDirectory)
                {
                    options.Properties[0] = OpenDialogProperty.openDirectory;
                }
                else if (selectDirectoryDTO.SelectFiles)
                {
                    options.Properties[0] = OpenDialogProperty.openFile;
                }

                options.Properties[1] = OpenDialogProperty.multiSelections;

                return(await Electron.Dialog.ShowOpenDialogAsync(Startup.MainWindow, options));
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }

            return(new string[] { });
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Note: On Windows and Linux an open dialog can not be both a file selector
        /// and a directory selector, so if you set properties to ['openFile', 'openDirectory']
        /// on these platforms, a directory selector will be shown.
        /// </summary>
        /// <param name="browserWindow">The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.</param>
        /// <param name="options"></param>
        /// <returns>An array of file paths chosen by the user</returns>
        public Task <string[]> ShowOpenDialogAsync(BrowserWindow browserWindow, OpenDialogOptions options)
        {
            var    taskCompletionSource = new TaskCompletionSource <string[]>();
            string guid = Guid.NewGuid().ToString();

            BridgeConnector.Socket.On("showOpenDialogComplete" + guid, (filePaths) =>
            {
                BridgeConnector.Socket.Off("showOpenDialogComplete" + guid);

                var result = ((JArray)filePaths).ToObject <string[]>();
                var list   = new List <string>();
                foreach (var item in result)
                {
                    list.Add(HttpUtility.UrlDecode(item));
                }
                taskCompletionSource.SetResult(list.ToArray());
            });


            BridgeConnector.Socket.Emit("showOpenDialog",
                                        JObject.FromObject(browserWindow, _jsonSerializer),
                                        JObject.FromObject(options, _jsonSerializer), guid);

            return(taskCompletionSource.Task);
        }
Ejemplo n.º 8
0
        private static void demo_Window_ShowOpenDialog()
        {
            OpenDialogOptions opts = default;

            opts                         = new OpenDialogOptions();
            opts.OpenLabel               = "Note: won't actually read from specified file path(s)";
            opts.Filters                 = new Dictionary <string, string[]>(2);
            opts.Filters["All"]          = new[] { "*" };
            opts.Filters["Dummy Filter"] = new[] { "dummy", "demo" };
            {
                opts.CanSelectFiles   = true;
                opts.CanSelectFolders = false;
                opts.CanSelectMany    = true;
            }
            logLn("Showing File-Open dialog...");
            vsc.Window.ShowOpenDialog(opts)((string[] filepaths) => {
                if ((null == filepaths))
                {
                    vsc.Window.ShowWarningMessage(logLn("Cancelled File-Open dialog, chicken?"), null);
                }
                else
                {
                    vsc.Window.ShowInformationMessage(logLn(strFmt("Selected {0} file path(s), excellent!", filepaths.Length)), null);
                }
            });
        }
Ejemplo n.º 9
0
    async void handleDestination(object sender, EventArgs args)
    {
        var dialog = await Dialog.Instance();

        // Create an OpenDialogOptions reference with custom Properties
        var openOptions = new OpenDialogOptions()
        {
            PropertyFlags = OpenDialogProperties.OpenDirectory | OpenDialogProperties.CreateDirectory
        };

        // Now show the open dialog passing in the options created previously
        // and a call back function when a file is selected.
        // If a call back function is not specified then the ShowOpenDialog function
        // will return an array of the selected file(s) or an empty array if no
        // files are selected.
        var destDirectory = await dialog.ShowOpenDialog(await BrowserWindow.GetFocusedWindow(),
                                                        openOptions
                                                        );

        if (destDirectory != null && destDirectory.Length > 0)
        {
            await destination.SetProperty("value", destDirectory[0]);

            await destination.DispatchEvent(changeEvent);
        }
    }
Ejemplo n.º 10
0
        private static void ListenForAddNewBook()
        {
            Electron.IpcMain.On("select-file", async(args) =>
            {
                var mainWindow = Electron.WindowManager.BrowserWindows.First();
                var options    = new OpenDialogOptions
                {
                    Properties = new OpenDialogProperty[] {
                        OpenDialogProperty.openFile
                    },
                    Filters = new FileFilter[] {
                        new FileFilter {
                            Extensions = new string[] { "*.epub" }, Name = "Archivos en formato Epub (*.epub)"
                        }
                    }
                };

                string[] files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
                if (files.Any())
                {
                    AddBookToLibrary(files.First());
                    Electron.IpcMain.Send(mainWindow, "select-file-reply");
                }
            });
        }
Ejemplo n.º 11
0
        public IActionResult Index()
        {
            if (HybridSupport.IsElectronActive)
            {
                Electron.IpcMain.On("select-directory", async(args) => {
                    var mainWindow = Electron.WindowManager.BrowserWindows.First();
                    var options    = new OpenDialogOptions
                    {
                        Properties = new OpenDialogProperty[] {
                            OpenDialogProperty.openFile,
                            //OpenDialogProperty.openDirectory
                        }
                    };

                    string[] files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
                    Electron.IpcMain.Send(mainWindow, "select-directory-reply", files);
                });

                Electron.IpcMain.On("error-dialog", (args) =>
                {
                    Electron.Dialog.ShowErrorBox("An Error Message", "Demonstrating an error message.");
                });

                Electron.IpcMain.On("information-dialog", async(args) =>
                {
                    var options = new MessageBoxOptions("This is an information dialog. Isn't it nice?")
                    {
                        Type    = MessageBoxType.info,
                        Title   = "Information",
                        Buttons = new string[] { "Yes", "No" }
                    };

                    var result = await Electron.Dialog.ShowMessageBoxAsync(options);

                    var mainWindow = Electron.WindowManager.BrowserWindows.First();
                    Electron.IpcMain.Send(mainWindow, "information-dialog-reply", result.Response);
                });

                Electron.IpcMain.On("save-dialog", async(args) =>
                {
                    var mainWindow = Electron.WindowManager.BrowserWindows.First();
                    var options    = new SaveDialogOptions
                    {
                        Title   = "Save an Image",
                        Filters = new FileFilter[]
                        {
                            new FileFilter {
                                Name = "Images", Extensions = new string[] { "jpg", "png", "gif" }
                            }
                        }
                    };

                    var result = await Electron.Dialog.ShowSaveDialogAsync(mainWindow, options);
                    Electron.IpcMain.Send(mainWindow, "save-dialog-reply", result);
                });
            }

            return(View());
        }
        public IActionResult Index()
        {
            if (!HybridSupport.IsElectronActive || saveAdded)
            {
                return(Ok());
            }

            Electron.IpcMain.On("save-dialog", async(args) =>
            {
                var mainWindow = Electron.WindowManager.BrowserWindows.First();
                var options    = new SaveDialogOptions
                {
                    Title   = "Export Keys as JSON file",
                    Filters = new FileFilter[]
                    {
                        new FileFilter {
                            Name       = "JSON",
                            Extensions = new string[] { "json" }
                        }
                    }
                };

                var result = await
                             Electron.Dialog.ShowSaveDialogAsync(mainWindow, options);
                Electron.IpcMain.Send(mainWindow, "save-dialog-reply", result);
            });

            Electron.IpcMain.On("open-dialog", async(args) =>
            {
                var mainWindow = Electron.WindowManager.BrowserWindows.First();
                var options    = new OpenDialogOptions
                {
                    Title   = "Import Keys as JSON file",
                    Filters = new FileFilter[]
                    {
                        new FileFilter {
                            Name       = "JSON",
                            Extensions = new string[] { "json" }
                        }
                    }
                };

                var result = await
                             Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
                Electron.IpcMain.Send(mainWindow, "open-dialog-reply", result);
            });

            saveAdded = true;

            return(Ok());
        }
Ejemplo n.º 13
0
        private async void SelectDirectory(string ipc)
        {
            var options = new OpenDialogOptions {
                Properties = new OpenDialogProperty[] {
                    OpenDialogProperty.openFile,
                    OpenDialogProperty.openDirectory
                }
            };
            var mainWindow = Electron.WindowManager.BrowserWindows.First();

            string[] files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);

            Reply(ipc, files);
        }
Ejemplo n.º 14
0
        public async Task ImportConfig()
        {
            var openoptions = new OpenDialogOptions()
            {
                Title   = "导入配置",
                Message = "请选择配置文件",
                Filters = new FileFilter[]
                {
                    new FileFilter()
                    {
                        Extensions = new string[] { "json" },
                        Name       = "JSON配置文件"
                    }
                },
            };
            var paths = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, openoptions);

            if (paths != null && paths.Length > 0 && !string.IsNullOrWhiteSpace(paths[0]))
            {
                try
                {
                    var local  = Path.Combine(Directory.GetCurrentDirectory(), "maps.json");
                    var remote = paths[0];

                    if (File.Exists(local))
                    {
                        var msgoptions = new MessageBoxOptions("是否覆盖当前的配置文件?")
                        {
                            Buttons = new string[] { "是", "否" },
                        };

                        var result = await Electron.Dialog.ShowMessageBoxAsync(mainWindow, msgoptions);

                        if (result.Response == 0)
                        {
                            File.Delete(local);
                        }
                        else
                        {
                            return;
                        }
                    }

                    File.Copy(remote, local);
                }
                catch (Exception)
                {
                }
            }
        }
Ejemplo n.º 15
0
        public async Task <string> OnSelectExportFolder()
        {
            var mainWindow            = Electron.WindowManager.BrowserWindows.First();
            OpenDialogOptions options = new OpenDialogOptions()
            {
                Properties = new ElectronNET.API.Entities.OpenDialogProperty[] { ElectronNET.API.Entities.OpenDialogProperty.openDirectory }
            };
            var folders = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);

            if (folders.Length > 0)
            {
                return(folders[0]);
            }
            return(String.Empty);
        }
Ejemplo n.º 16
0
        public static async Task <string> GetSelectPath()
        {
            var mainWindow = Electron.WindowManager.BrowserWindows.First();
            var options    = new OpenDialogOptions
            {
                Properties = new OpenDialogProperty[]
                {
                    OpenDialogProperty.openFile,
                    OpenDialogProperty.openDirectory
                }
            };

            string[] files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);

            return(string.Join("", files));
        }
Ejemplo n.º 17
0
        public static async Task NewFileAsync()
        {
            var mainWindow = Electron.WindowManager.BrowserWindows.First();

            var options = new OpenDialogOptions
            {
                Title      = "New File",
                Properties = new OpenDialogProperty[] {
                    OpenDialogProperty.openFile,
                    OpenDialogProperty.promptToCreate,
                }
            };

            var files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);

            var filePath = files.FirstOrDefault();

            if (filePath == default)
            {
                return;
            }

            if (ApplicationState.Instance.FileHandlerInstance.GetOpenFilePaths().Contains(filePath))
            {
                Electron.Dialog.ShowErrorBox("File Error", "File already exists.");
                return;
            }

            var task = new Task(() =>
            {
                try
                {
                    ApplicationState.Instance.FileHandlerInstance.NewFile(filePath);
                    ApplicationState.Instance.FileHandlerInstance.GetFileBuffer(filePath).FillBufferFromFile();
                    var handler = OpenFilesChanged;
                    handler?.Invoke(ApplicationState.Instance.FileHandlerInstance.GetOpenFilePaths(), EventArgs.Empty);
                }
                catch (Exception e)
                {
                    Electron.Dialog.ShowErrorBox("File Error", "File already exists.");
                    Console.WriteLine(e.StackTrace);
                }
            });

            task.Start();
            await task;
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Note: On Windows and Linux an open dialog can not be both a file selector
        /// and a directory selector, so if you set properties to ['openFile', 'openDirectory']
        /// on these platforms, a directory selector will be shown.
        /// </summary>
        /// <param name="browserWindow"></param>
        /// <param name="options"></param>
        /// <returns>An array of file paths chosen by the user</returns>
        public Task <string[]> ShowOpenDialogAsync(BrowserWindow browserWindow, OpenDialogOptions options)
        {
            var taskCompletionSource = new TaskCompletionSource <string[]>();

            BridgeConnector.Socket.On("showOpenDialogComplete", (filePaths) =>
            {
                BridgeConnector.Socket.Off("showOpenDialogComplete");

                var result = ((JArray)filePaths).ToObject <string[]>();
                taskCompletionSource.SetResult(result);
            });

            BridgeConnector.Socket.Emit("showOpenDialog",
                                        JObject.FromObject(browserWindow, _jsonSerializer),
                                        JObject.FromObject(options, _jsonSerializer));

            return(taskCompletionSource.Task);
        }
Ejemplo n.º 19
0
        public void OnGet()
        {
            Electron.IpcMain.On("assemblyPathBtn-selectDirectory", async(args) => {
                var mainWindow = Electron.WindowManager.BrowserWindows.First();
                var options    = new OpenDialogOptions
                {
                    Properties = new OpenDialogProperty[] {
                        OpenDialogProperty.openFile
                    }
                };

                string[] files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
                Electron.IpcMain.Send(mainWindow, "assemblyPath-reply", files);
            });

            Electron.IpcMain.On("destinationPathBtn-selectDirectory", async(args) => {
                var mainWindow = Electron.WindowManager.BrowserWindows.First();
                var options    = new OpenDialogOptions
                {
                    Properties = new OpenDialogProperty[] {
                        OpenDialogProperty.openDirectory
                    }
                };

                string[] files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
                Electron.IpcMain.Send(mainWindow, "destinationPathBtn-reply", files);
            });

            Electron.IpcMain.On("generate-schema", async(args) => {
                dynamic arguments    = args;
                var assemblyFilePath = arguments.paths[0].Value;
                var destinationPath  = arguments.paths[1].Value;

                var protoFileGenerator = new ProtoFileGenerator();
                protoFileGenerator.SaveProtoFile(assemblyFilePath, destinationPath);

                var options = new MessageBoxOptions("Successfull generated!")
                {
                    Type  = MessageBoxType.info,
                    Title = "Information"
                };
                await Electron.Dialog.ShowMessageBoxAsync(options);
            });
        }
Ejemplo n.º 20
0
        /// <inheritdoc />
        public async Task LoadImagesAsync()
        {
            var openDialogOptions = new OpenDialogOptions
            {
                Title      = Translator.Translate("Please choose your Images"),
                Properties = new[] { OpenDialogProperty.openFile, OpenDialogProperty.multiSelections },
                Filters    = new[]
                {
                    new FileFilter
                    {
                        Extensions = new[] { "jpg", "png", "gif" }, Name = Translator.Translate("Images")
                    }
                }
            };
            var imageFilePaths = await ElectronHelper.ShowOpenDialogAsync(ElectronHelper.GetBrowserWindow(), openDialogOptions);

            if (imageFilePaths != null && imageFilePaths.Any())
            {
                await CurrentProject.AddImagesAsync(imageFilePaths);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Note: On Windows and Linux an open dialog can not be both a file selector
        /// and a directory selector, so if you set properties to ['openFile', 'openDirectory']
        /// on these platforms, a directory selector will be shown.
        /// </summary>
        /// <param name="browserWindow">The browserWindow argument allows the dialog to attach itself to a parent window, making it modal.</param>
        /// <param name="options"></param>
        /// <returns>An array of file paths chosen by the user</returns>
        public Task <string[]> ShowOpenDialogAsync(BrowserWindow browserWindow, OpenDialogOptions options)
        {
            var    taskCompletionSource = new TaskCompletionSource <string[]>(TaskCreationOptions.RunContinuationsAsynchronously);
            string guid = Guid.NewGuid().ToString();

            BridgeConnector.On <string[]>("showOpenDialogComplete" + guid, (filePaths) =>
            {
                BridgeConnector.Off("showOpenDialogComplete" + guid);

                var list = new List <string>();

                foreach (var item in filePaths)
                {
                    list.Add(HttpUtility.UrlDecode(item));
                }
                taskCompletionSource.SetResult(list.ToArray());
            });

            BridgeConnector.Emit("showOpenDialog", browserWindow, options, guid);

            return(taskCompletionSource.Task);
        }
Ejemplo n.º 22
0
        /// <inheritdoc />
        public async Task LoadProjectAsync()
        {
            var openDialogOptions = new OpenDialogOptions
            {
                Title      = Translator.Translate("Please choose your Project File"),
                Properties = new[] { OpenDialogProperty.openFile },
                Filters    = new[]
                {
                    new FileFilter
                    {
                        Extensions = new[] { "json" }, Name = Translator.Translate("Project File")
                    }
                }
            };

            var projectFilePath = (await ElectronHelper.ShowOpenDialogAsync(ElectronHelper.GetBrowserWindow(), openDialogOptions))
                                  .FirstOrDefault();

            if (!string.IsNullOrWhiteSpace(projectFilePath))
            {
                await CurrentProject.LoadAsync(projectFilePath);
            }
        }
        public IActionResult Index()
        {
            if (HybridSupport.IsElectronActive)
            {
                Electron.IpcMain.On("start-hoosthook", async(args) =>
                {
                    var mainWindow = Electron.WindowManager.BrowserWindows.First();
                    var options    = new OpenDialogOptions
                    {
                        Properties = new OpenDialogProperty[]
                        {
                            OpenDialogProperty.openDirectory
                        }
                    };
                    var folderPath = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);

                    var resultFromTypeScript = await Electron.HostHook.CallAsync <string>("create-excel-file", folderPath);
                    Electron.IpcMain.Send(mainWindow, "excel-file-created", resultFromTypeScript);
                });
            }

            return(View());
        }
Ejemplo n.º 24
0
    async void handleSource(object sender, EventArgs args)
    {
        var dialog = await Dialog.Instance();

        // Create an OpenDialogOptions reference with custom FileFilters
        var openOptions = new OpenDialogOptions()
        {
            Filters = new FileFilter[]
            {
                //new FileFilter() { Name = "All Files", Extensions = new string[] {"*"} },
                new FileFilter()
                {
                    Name = "Movies", Extensions = new string[] { "mkv", "avi" }
                },
            }
        };

        // Now show the open dialog passing in the options created previously
        // and a call back function when a file is selected.
        // If a call back function is not specified then the ShowOpenDialog function
        // will return an array of the selected file(s) or an empty array if no
        // files are selected.
        var sourceFile = await dialog.ShowOpenDialog(await BrowserWindow.GetFocusedWindow(),
                                                     openOptions
                                                     );

        if (sourceFile != null && sourceFile.Length > 0)
        {
            await source.SetProperty("value", sourceFile[0]);

            await name.SetProperty("value", Path.GetFileNameWithoutExtension(sourceFile[0]) + ".m4v");

            await source.DispatchEvent(changeEvent);

            await ipcRenderer.Send("getMetaData", sourceFile[0]);
        }
    }
Ejemplo n.º 25
0
        public IActionResult Index()
        {
            Electron.IpcMain.On("SayHello", async(args) =>
            {
                Electron.Notification.Show(new NotificationOptions("Hallo Robert", "Nachricht von ASP.NET Core App"));
                Electron.IpcMain.Send(Electron.WindowManager.BrowserWindows.First(), "Goodbye", "Elephant!");

                var currentBrowserWindow = Electron.WindowManager.BrowserWindows.First();
                var openDialogOptions    = new OpenDialogOptions
                {
                    Title       = "Wuhuuu",
                    ButtonLabel = "Mhh Okay",
                    DefaultPath = await Electron.App.GetPathAsync(PathName.pictures),
                    Message     = "Hello World",
                    Properties  = new OpenDialogProperty[] { OpenDialogProperty.openDirectory }
                };
                var filePaths = await Electron.Dialog.ShowOpenDialogAsync(currentBrowserWindow, openDialogOptions);
            });

            Electron.IpcMain.On("GetPath", async(args) =>
            {
                var currentBrowserWindow = Electron.WindowManager.BrowserWindows.First();

                string pathName = await Electron.App.GetPathAsync(PathName.pictures);
                Electron.IpcMain.Send(currentBrowserWindow, "GetPathComplete", pathName);

                currentBrowserWindow.Minimize();
                await Electron.WindowManager.CreateWindowAsync(new BrowserWindowOptions {
                    Title           = "My second Window",
                    AutoHideMenuBar = true
                }, "http://www.google.de");
            });


            return(View());
        }
Ejemplo n.º 26
0
        private static async void SelectDirectory(dynamic args)
        {
            string id           = args.id.ToString();
            string functionName = args.functionName.ToString();

            OpenDialogOptions options = new OpenDialogOptions
            {
                Properties = new[]
                {
                    OpenDialogProperty.openDirectory
                }
            };

            string[] directory = await Electron.Dialog.ShowOpenDialogAsync(MainWindow, options);

            dynamic directoryReply = new JObject();

            directoryReply.id = id;

            directoryReply.directory    = directory.Length > 0 ? directory.First() : string.Empty;
            directoryReply.functionName = functionName;

            Electron.IpcMain.Send(MainWindow, Messages.DIRECTORY_SELECTED, directoryReply);
        }
Ejemplo n.º 27
0
    /// <summary>
    /// Default entry into managed code.
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task <object> Invoke(object input)
    {
        if (console == null)
        {
            console = await WebSharpJs.NodeJS.Console.Instance();
        }

        try
        {
            // Since we are executing from the Renderer process we have to use
            // dialog remote process.
            dialog = await Dialog.Instance();

            var page = new HtmlPage();
            document = await page.GetDocument();

            // Get the HtmlElement with the id of "openFile"
            var openFile = await document.GetElementById("openFile");

            // Attach a "click" event handler to the openFile HtmlElement
            await openFile.AttachEvent("click", new EventHandler(async(sender, evt) =>
            {
                // Create an OpenDialogOptions reference with custom FileFilters
                var openOptions = new OpenDialogOptions()
                {
                    Filters = new FileFilter[]
                    {
                        new FileFilter()
                        {
                            Name = "text", Extensions = new string[] { "txt" }
                        },
                        new FileFilter()
                        {
                            Name = "All Files", Extensions = new string[] { "*" }
                        }
                    }
                };

                // Now show the open dialog passing in the options created previously
                // and a call back function when a file is selected.
                // If a call back function is not specified then the ShowOpenDialog function
                // will return an array of the selected file(s) or an empty array if no
                // files are selected.
                await dialog.ShowOpenDialog(
                    openOptions,
                    openFileCallback
                    );
            }
                                                                 ));

            // Get the HtmlElement with the id of "saveFile"
            var saveFile = await document.GetElementById("saveFile");

            // Attach a "click" event handler to the saveFile HtmlElement
            await saveFile.AttachEvent("click", new EventHandler(async(sender, evt) =>
            {
                // Create an OpenDialogOptions reference with custom FileFilters
                var saveOptions = new SaveDialogOptions()
                {
                    Filters = new FileFilter[]
                    {
                        new FileFilter()
                        {
                            Name = "text", Extensions = new string[] { "txt" }
                        },
                        new FileFilter()
                        {
                            Name = "All Files", Extensions = new string[] { "*" }
                        }
                    }
                };

                // Now show the save dialog passing in the options created previously
                // and a call back function to be called when the save button is clicked.
                // If a call back function is not specified then the ShowSaveDialog function
                // will return a string or an empty string if no file was specified.
                await dialog.ShowSaveDialog(
                    saveOptions,
                    saveFileCallback
                    );
            }
                                                                 ));
        }
        catch (Exception exc) { await dialog.ShowErrorBox("There was an error: ", exc.Message); }

        return(null);
    }
Ejemplo n.º 28
0
        public IActionResult Index()
        {
            try
            {
                if (HybridSupport.IsElectronActive)
                {
                    //Responds to user selecting a directory
                    Electron.IpcMain.On("select-directory", async(args) =>
                    {
                        var mainWindow = Electron.WindowManager.BrowserWindows.First();
                        //creates a seperate window for choosing the directory path
                        var options = new OpenDialogOptions
                        {
                            Properties = new OpenDialogProperty[] {
                                OpenDialogProperty.openFile,
                                OpenDialogProperty.openDirectory
                            }
                        };
                        //the result is saved as a string[]
                        string[] files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
                        //the result is then converted to a string
                        string path = String.Join("", files);
                        //if the path is valid and contains content...
                        if (BEP.CheckIfPathValid(path) && BEP.CheckIfPathContainsContent(path))
                        {
                            //index it, it's the new corpus
                            BEP.GetIndex(path);
                            //send message to the view
                            Electron.IpcMain.Send(mainWindow, "select-directory-reply", "true");
                        }
                        //otherwise, if the path does not exist...
                        else if (!BEP.CheckIfPathValid(path))
                        {
                            //send a message to the view
                            Electron.IpcMain.Send(mainWindow, "select-directory-reply", "invalidPath");
                        }
                        else
                        {
                            //sends a message to the view
                            Electron.IpcMain.Send(mainWindow, "select-directory-reply", "emptyFile");
                        }
                    });

                    //Responds to user choosing to stem a term
                    Electron.IpcMain.On("stemTerm", (args) =>
                    {
                        var mainWindow = Electron.WindowManager.BrowserWindows.First();
                        //turns argument into a string
                        string term = args.ToString();
                        //stems the argument
                        string stemmedTerm = BEP.StemTerm(term);
                        //sends result back to the view
                        Electron.IpcMain.Send(mainWindow, "stemmedTerm", stemmedTerm);
                    });

                    //Responds to user desiring to get info on Habeas
                    Electron.IpcMain.On("info-dialog", async(args) =>
                    {
                        //set details of message box
                        var options = new MessageBoxOptions
                                      (
                            "Habeas supports" + Environment.NewLine + Environment.NewLine +
                            "1. single query" + Environment.NewLine +
                            "2. boolean query -> put a space between keywords for AND queries, put a '+' for OR queries" + Environment.NewLine +
                            "3. phrase query -> \"term1 term2...\"" + Environment.NewLine +
                            "4. near query -> [term1 NEAR/k term2]" + Environment.NewLine +
                            "5. wildcard query -> colo*r" + Environment.NewLine +
                            "6. soundex for author name" + Environment.NewLine + Environment.NewLine +
                            "To STEM a word, select 'stem' on the dropdown to the left of the search field. Then type the word you wish to stem into the search field and click the enter button." + Environment.NewLine + Environment.NewLine + "To view the VOCAB list for an index, click the 'Vocab' label on the navigation bar." + Environment.NewLine + Environment.NewLine + "To INDEX a new directory, click the 'Index' label on the navigation bar."
                                      )
                        {
                            Type  = MessageBoxType.info,
                            Title = "Information"
                        };
                        //creates message box from options
                        var result     = await Electron.Dialog.ShowMessageBoxAsync(options);
                        var mainWindow = Electron.WindowManager.BrowserWindows.First();
                        //sends message box to the main window
                        Electron.IpcMain.Send(mainWindow, "information-dialog-reply", result.Response);
                    });

                    //Responds to user attempting to get the vocab list from the corpus
                    Electron.IpcMain.On("chooseVocab", (args) =>
                    {
                        //has backend get 1000 vocab terms
                        List <String> result = BEP.PrintVocab(1000);
                        var mainWindow       = Electron.WindowManager.BrowserWindows.First();
                        //send list to view
                        Electron.IpcMain.Send(mainWindow, "vocabList", result);
                    });

                    //Responds to user searching the corpus
                    Electron.IpcMain.On("searchText", (args) =>
                    {
                        var mainWindow = Electron.WindowManager.BrowserWindows.First();
                        //terms argument into string
                        string term = args.ToString();
                        //gets list of posting titles from backend
                        List <string> Postings = BEP.SearchQuery(term);
                        foreach (string item in Postings)
                        {
                            Console.WriteLine(item);
                        }
                        //sends results to view
                        Electron.IpcMain.Send(mainWindow, "searchText", Postings);
                    });

                    //Responds to user doing a soundex search
                    Electron.IpcMain.On("soundexText", (args) =>
                    {
                        var mainWindow = Electron.WindowManager.BrowserWindows.First();
                        //turns argument into string
                        string term = args.ToString();
                        //gets list of strings from backend
                        List <string> Postings = BEP.SearchSoundexQuery(term);
                        //sends results to view
                        Electron.IpcMain.Send(mainWindow, "soundexText", Postings);
                    });

                    //
                    Electron.IpcMain.On("RetType", async(args) =>
                    {
                        //set details of message box
                        var options = new MessageBoxOptions
                                      (
                            "Select Ranked Retrieval type" + Environment.NewLine
                                      )
                        {
                            Type    = MessageBoxType.info,
                            Title   = "RetrievalType",
                            Buttons = new string[] { "Default", "Tf-Idf", "Okapi", "Wacky" }
                        };
                        //creates message box from options
                        var result = await Electron.Dialog.ShowMessageBoxAsync(options);
                        switch (result.Response)
                        {
                        case 0:
                            BEP.selectRetrieval("Default");
                            break;

                        case 1:
                            BEP.selectRetrieval("Tf-idf");
                            break;

                        case 2:
                            BEP.selectRetrieval("Okapi");
                            break;

                        case 3:
                            BEP.selectRetrieval("Wacky");
                            break;
                        }
                    });

                    //Responds to user attempting to read a document
                    Electron.IpcMain.On("readDoc", (args) =>
                    {
                        //argument is turned into string
                        string term = args.ToString();
                        //content of document retrieved from backend
                        string Content = BEP.GetDocContent(term);
                        //creates message box out of document content
                        var options = new MessageBoxOptions(
                            Content
                            )
                        {
                            Type  = MessageBoxType.none,
                            Title = BEP.GetDocTitle(term)
                        };
                        var result     = Electron.Dialog.ShowMessageBoxAsync(options);
                        var mainWindow = Electron.WindowManager.BrowserWindows.First();
                    });

                    Electron.IpcMain.On("modeSwitch", (args) =>
                    {
                        BEP.switchMode();
                    });
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return(View());
        }
Ejemplo n.º 29
0
        public IActionResult Index()
        {
            if (HybridSupport.IsElectronActive)
            {
                Electron.IpcMain.On("select-file-path", async(args) =>
                {
                    var mainWindow = Electron.WindowManager.BrowserWindows.First();
                    var options    = new OpenDialogOptions
                    {
                        Properties = new OpenDialogProperty[]
                        {
                            OpenDialogProperty.openFile,
                        }
                    };

                    string[] files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
                    Electron.IpcMain.Send(mainWindow, "select-file-path-reply", files);
                });

                Electron.IpcMain.On("select-schema-path", async(args) =>
                {
                    var mainWindow = Electron.WindowManager.BrowserWindows.First();
                    var options    = new OpenDialogOptions
                    {
                        Properties = new OpenDialogProperty[] {
                            OpenDialogProperty.openFile
                        },
                        Filters = new FileFilter[]
                        {
                            new FileFilter
                            {
                                Name       = "Json schema",
                                Extensions = new string[] { "json" }
                            }
                        }
                    };

                    string[] files = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
                    Electron.IpcMain.Send(mainWindow, "select-schema-path-reply", files);
                });

                Electron.IpcMain.On("validate-file-btn", (args) =>
                {
                    var mainWindow = Electron.WindowManager.BrowserWindows.First();
                    try
                    {
                        args           = args.ToString().Replace(@"\", @"\\");
                        var arguments  = JsonConvert.DeserializeObject <FileDefinition>(args.ToString());
                        var filePath   = arguments.FilePath;
                        var schemaPath = arguments.SchemaFilePath;
                        var fileType   = arguments.FileType;
                        if (!System.IO.File.Exists(filePath))
                        {
                            Electron.IpcMain.Send(mainWindow, "results", $"<div class='alert alert-danger' role='alert'>Invalid file {filePath}</div>");
                            return;
                        }
                        if (!System.IO.File.Exists(schemaPath))
                        {
                            Electron.IpcMain.Send(mainWindow, "results", $"<div class='alert alert-danger' role='alert'>Invalid file {schemaPath}</div>");
                            return;
                        }

                        var schemaData   = string.Empty;
                        var schemaParser = new SchemaParser();
                        try
                        {
                            using (var sr = new StreamReader(System.IO.File.OpenRead(schemaPath)))
                            {
                                schemaData = sr.ReadToEnd();
                            }
                        }
                        catch (Exception ex)
                        {
                            var errorMsg = String.Format(null, SharedResources.SchemaError, ex.Message);
                            Console.WriteLine($"{errorMsg}");
                        }

                        if (string.IsNullOrEmpty(schemaData))
                        {
                            Electron.IpcMain.Send(mainWindow, "results", "<div class='alert alert-danger' role='alert'>Schema file is empty.</div>");
                            return;
                        }

                        var parsedSchema            = schemaParser.ParseSchema(schemaData);
                        var schemaValidator         = new FluentSchemaValidator();
                        var schemaValidationResults = schemaValidator.Validate(parsedSchema);
                        if (!schemaValidationResults.IsValid && schemaValidationResults.Errors.Any())
                        {
                            var results = _viewRenderService.RenderToStringAsync("Partial/_SchemaFileValidationResult", schemaValidationResults.Errors);
                            if (results.IsCompletedSuccessfully && !results.IsFaulted)
                            {
                                Electron.IpcMain.Send(mainWindow, "results", results.Result);
                                return;
                            }
                            else
                            {
                                Electron.IpcMain.Send(mainWindow, "results", "<div class='alert alert-danger' role='alert'>An Error has occurred while processing the file. Please contact your administrator.</div>");
                                return;
                            }
                        }

                        if (parsedSchema.FileFormat.ToLower() == "fixed")
                        {
                            var validator  = new FixedLengthFileValidator(filePath, schemaPath, parsedSchema);
                            var result     = validator.ValidateFile();
                            result.Results = result.Results.Take(50).ToList();
                            var results    = _viewRenderService.RenderToStringAsync("Partial/_FixedLengthFileValidationResult", result);
                            if (results.IsCompletedSuccessfully && !results.IsFaulted)
                            {
                                Electron.IpcMain.Send(mainWindow, "results", results.Result);
                                return;
                            }
                            else
                            {
                                Electron.IpcMain.Send(mainWindow, "results", "<div class='alert alert-danger' role='alert'>An Error has occurred while processing the file. Please contact your administrator.</div>");
                                return;
                            }
                        }
                        else if (parsedSchema.FileFormat.ToLower() == "separated")
                        {
                            var validator  = new SeparatedFileValidator(filePath, schemaPath, parsedSchema);
                            var result     = validator.ValidateFile();
                            result.Results = result.Results.Take(50).ToList();
                            var results    = _viewRenderService.RenderToStringAsync("Partial/_SeparatedFileValidationResult", result);
                            if (results.IsCompletedSuccessfully && !results.IsFaulted)
                            {
                                Electron.IpcMain.Send(mainWindow, "results", results.Result);
                                return;
                            }
                            else
                            {
                                Electron.IpcMain.Send(mainWindow, "results", "<div class='alert alert-danger' role='alert'>An Error has occurred while processing the file. Please contact your administrator.</div>");
                                return;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Electron.IpcMain.Send(mainWindow, "results", $"<div class='alert alert-danger' role='alert'>{ex.Message.ToString()}</div>");
                        return;
                    }
                });

                Electron.IpcMain.On("create-html-file", async(args) =>
                {
                    var mainWindow = Electron.WindowManager.BrowserWindows.First();
                    var options    = new OpenDialogOptions
                    {
                        Properties = new OpenDialogProperty[]
                        {
                            OpenDialogProperty.openDirectory,
                        }
                    };

                    string[] directories = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);
                    var directory        = directories[0];
                    var pathString       = Path.Combine(directory, "Validation_Result.html");
                    var file             = System.IO.File.Create(pathString);
                    file.Close();
                    Electron.IpcMain.Send(mainWindow, "created-html-file-reply", pathString);
                });
            }

            return(View());
        }
        public IActionResult Index()
        {
            if (HybridSupport.IsElectronActive)
            {
                var menu = new MenuItem[] {
                    new MenuItem {
                        Label = "File", Submenu = new MenuItem[] {
                            new MenuItem {
                                Label       = "Open HTML",
                                Accelerator = "CmdOrCtrl+O",
                                Click       = async() =>
                                {
                                    // Open file HTML
                                    var mainWindow = Electron.WindowManager.BrowserWindows.First();
                                    var options    = new OpenDialogOptions
                                    {
                                        Title   = "Open HTML file",
                                        Filters = new FileFilter[]
                                        {
                                            new FileFilter {
                                                Name = "HTML", Extensions = new string[] { "html", "htm" }
                                            }
                                        }
                                    };

                                    var result = await Electron.Dialog.ShowOpenDialogAsync(mainWindow, options);

                                    if (result.Count() != 0)
                                    {
                                        string OpenfilePath = result.First();
                                        string strContent   = FileOperation.openRead(OpenfilePath);

                                        //Call Render JS
                                        var mainWindow1 = Electron.WindowManager.BrowserWindows.First();
                                        Electron.IpcMain.Send(mainWindow1, "setContent", strContent);

                                        mainWindow.SetTitle(OpenfilePath);
                                    }
                                }
                            },
                            new MenuItem {
                                Label       = "Save HTML",
                                Accelerator = "CmdOrCtrl+S",
                                Click       = async() =>
                                {
                                    var mainWindow = Electron.WindowManager.BrowserWindows.First();

                                    Electron.IpcMain.Send(mainWindow, "saveContent");
                                }
                            },
                            new MenuItem {
                                Type = MenuType.separator
                            },
                            new MenuItem {
                                Label       = "Exit",
                                Accelerator = "CmdOrCtrl+X",
                                Click       = () =>
                                {
                                    // Exit app
                                    Electron.App.Exit();
                                }
                            },
                        }
                    },
                    new MenuItem {
                        Label = "Help", Submenu = new MenuItem[] {
                            new MenuItem
                            {
                                Label       = "About",
                                Accelerator = "CmdOrCtrl+R",
                                Click       = async() =>
                                {
                                    // open native  message  windows
                                    var options = new MessageBoxOptions("This is a demo application for Electron.NEt and .NET CORE 3.");
                                    options.Type  = MessageBoxType.info;
                                    options.Title = "About HTMLEditor";

                                    await Electron.Dialog.ShowMessageBoxAsync(options);
                                }
                            }
                        }
                    }
                };

                Electron.Menu.SetApplicationMenu(menu);
            }

            return(View());
        }