private async void Delete()
        {
            Log.Info(LogMessages.ManageDataSetDeleteCommand);
            if (SelectedDataSet == null)
            {
                return;
            }
            var context = new CommonDialogViewModel
            {
                Buttons = ButtonsEnum.YesNo,
                Header  = "Delete dataset",
                Content = new JContent("Are you sure to remove the following data set: " + SelectedDataSet.Name)
            };
            var view = new CommonDialog {
                DataContext = context
            };
            var canClose = false;
            var result   = await _dialogHandler.Show(view, "RootDialog",
                                                     async (object sender, DialogClosingEventArgs args) =>
            {
                if (!canClose && (CommonDialogResult)args.Parameter == CommonDialogResult.Yes)
                {
                    args.Cancel();
                    args.Session.UpdateContent(new ProgressDialog());
                    var isSuccessful = false;
                    var errorMessage = "";
                    try
                    {
                        var response = await _dataSetManager.DeleteDataSetAsync(SelectedDataSet.Name);
                        isSuccessful = response.IsSuccessful;
                        ResponseValidator.Validate(response, false);
                    }
                    catch (Exception exception)
                    {
                        isSuccessful = false;
                        errorMessage = exception.Message;
                    }
                    finally
                    {
                        if (!isSuccessful)
                        {
                            context.ErrorMessage = errorMessage;
                            context.ShowError    = true;
                            args.Session.UpdateContent(view);
                        }
                        else
                        {
                            canClose = true;
                            args.Session.Close((CommonDialogResult)args.Parameter);
                        }
                    }
                }
            });

            if ((CommonDialogResult)result == CommonDialogResult.Yes)
            {
                DispatcherHelper.CheckBeginInvokeOnUI(() => DataSets.Remove(SelectedDataSet));
            }
        }
Example #2
0
        /// <summary>
        /// Initializes a new instance of the ManageProcessViewModel class.
        /// </summary>
        public ManageProcessViewModel(IProcessManager processManager, DialogHandler dialogHandler)
        {
            _processManager = processManager;
            _dialogHandler  = dialogHandler;

            Messenger.Default.Register <UpdateMessage>(this, message =>
            {
                switch (message.UpdateType)
                {
                case UpdateType.NewProcessCreated:
                    var processes        = Processes.ToList();
                    var currentProcess   = (Process)message.Parameter;
                    currentProcess.Start = currentProcess.Start.ToLocalTime();
                    currentProcess.End   = currentProcess.End.ToLocalTime();
                    processes.Add(currentProcess);
                    DispatcherHelper.CheckBeginInvokeOnUI(() => Processes = new ObservableCollection <Process>(processes.OrderByDescending(p => p.Start)));
                    break;
                }
            });

            LoadedCommand = new RelayCommand(async() =>
            {
                try
                {
                    Mouse.SetCursor(Cursors.Arrow);
                    SetGridSettings();
                    if (_loadedFirst && _processManager != null)
                    {
                        _loadedFirst = false;
                        await _dialogHandler.ShowProgress(null, async() =>
                        {
                            DispatcherHelper.CheckBeginInvokeOnUI(() => Processes.Clear());
                            Log.Info(LogMessages.ManageProcessLoadProcesses);
                            var response = await _processManager.GetProcessesAsync(true);
                            if (ResponseValidator.Validate(response, false))
                            {
                                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                                {
                                    if (response.ResponseObject.Any())
                                    {
                                        var ordered = response.ResponseObject.OrderByDescending(p => p.Start);
                                        Processes   = new ObservableCollection <Process>(ordered.Select(p =>
                                        {
                                            p.Start = p.Start.ToLocalTime();
                                            p.End   = p.End.ToLocalTime();
                                            return(p);
                                        }));
                                        RaisePropertyChanged("Processes");
                                    }
                                });
                            }
                        });
                    }
                }
                catch (Exception exception)
                {
                    Messenger.Default.Send(exception);
                }
            });

            RefreshProcessCommand = new RelayCommand <string>(async id =>
            {
                try
                {
                    var processResponse = await _processManager.GetProcessAsync(id);
                    if (ResponseValidator.Validate(processResponse, false))
                    {
                        var selectedItem = Processes.FirstOrDefault(p => p.Id == id);
                        if (selectedItem != null)
                        {
                            Processes[Processes.IndexOf(selectedItem)] = processResponse.ResponseObject;
                            Processes = new ObservableCollection <Process>(Processes);
                        }
                    }
                }
                catch (Exception exception)
                {
                    Messenger.Default.Send(exception);
                }
            });

            CancelProcessCommand = new RelayCommand <Process>(async process =>
            {
                try
                {
                    var processResponse = await _processManager.CancelProcessAsync(process.Id);
                    if (ResponseValidator.Validate(processResponse, false))
                    {
                        var selectedItem = Processes.FirstOrDefault(p => p.Id == process.Id);
                        if (selectedItem != null)
                        {
                            selectedItem.Status = ProcessStatusEnum.Cancelled;
                            Processes           = new ObservableCollection <Process>(Processes);
                        }
                    }
                }
                catch (Exception exception)
                {
                    Messenger.Default.Send(exception);
                }
            });

            ShowProcessDetailsCommand = new RelayCommand <Process>(async process =>
            {
                if (process == null)
                {
                    return;
                }
                var context = new CommonDialogViewModel
                {
                    Header  = "Process details",
                    Buttons = ButtonsEnum.Ok,
                    Content = new JContent(process)
                };
                var view = new CommonDialog {
                    DataContext = context
                };
                await _dialogHandler.Show(view);
            });
        }
Example #3
0
        /// <summary>
        /// Initializes a new instance of the ConnectViewModel class.
        /// </summary>
        public ConnectViewModel()
        {
            _dialogHandler = new DialogHandler();
            Endpoints      = new ObservableCollection <ConfigurationWithId>(GlobalStore.Endpoints);
            SelectedIndex  = Endpoints.IndexOf(Endpoints.FirstOrDefault(ep => ep.Equals(GlobalStore.SelectedEndpoint)));
            SelectCommand  = new RelayCommand(async() =>
            {
                if (SelectedIndex < 0)
                {
                    return;
                }
                ClientResponseWithObject <Status> response = null;
                bool IsSuccessFul = false;
                await
                _dialogHandler.Show(new ProgressDialog(), "ConnectDialog",
                                    async(object s, DialogOpenedEventArgs arg) =>
                {
                    try
                    {
                        var statusManager = new StatusManager(Endpoints[SelectedIndex]);
                        response          = await statusManager.GetStatusAsync();
                        IsSuccessFul      = response.IsSuccessful;
                    }
                    catch (Exception exception)
                    {
                        IsSuccessFul = false;
                    }
                    finally
                    {
                        arg.Session.Close();
                    }
                });


                if (IsSuccessFul)
                {
                    var tauVersion        = Assembly.GetExecutingAssembly().GetName().Version;
                    var apiVersion        = Version.Parse(response.ApiVersion);
                    var isVersionMismatch = tauVersion.Major != apiVersion.Major || tauVersion.Minor != apiVersion.Minor;
                    object result         = null;
                    if (isVersionMismatch)
                    {
                        result = await _dialogHandler.Show(new CommonDialog
                        {
                            DataContext =
                                new CommonDialogViewModel
                            {
                                Buttons = ButtonsEnum.YesNo,
                                Header  = "Warning! Version mismatch.",
                                Content = new Message($"Api version: {apiVersion}{Environment.NewLine}Tau version:{tauVersion}.{Environment.NewLine}Would you like to continue?")
                            }
                        }, "ConnectDialog");
                    }
                    if (!isVersionMismatch || (CommonDialogResult)result == CommonDialogResult.Yes)
                    {
                        GlobalStore.SelectedEndpoint = Endpoints[SelectedIndex];
                        await((ViewModelLocator)App.Current.Resources["Locator"]).EndpointUpdate();
                        var mainVindow         = new MainWindow();
                        var connectWindow      = App.Current.MainWindow;
                        App.Current.MainWindow = mainVindow;
                        mainVindow.Show();
                        connectWindow.Close();
                    }
                }
                else
                {
                    await
                    _dialogHandler.Show(
                        new CommonDialog
                    {
                        DataContext =
                            new CommonDialogViewModel
                        {
                            Header  = "Warning!",
                            Content = new Message(
                                $"Failed to connect to selected endpoint.{Environment.NewLine}{(response?.Errors == null ? "" : string.Join(Environment.NewLine, response.Errors.Errors))}"),
                            Buttons = ButtonsEnum.Ok
                        }
                    }, "ConnectDialog");
                }
            });
            NewCommand = new RelayCommand(async() =>
            {
                var context = new CommonDialogViewModel
                {
                    Buttons = ButtonsEnum.OkCancel,
                    Header  = "Create new endpoint",
                    Content = new JContent(new { ApiBaseEndpoint = new Uri("https://europe.slamby.com/"), ApiSecret = "", ParallelLimit = 0, BulkSize = 1000 })
                };
                var view = new CommonDialog {
                    DataContext = context
                };
                var canClose = false;
                var result   = await _dialogHandler.Show(view, "ConnectDialog",
                                                         async(object sender, DialogClosingEventArgs args) =>
                {
                    if (!canClose && (CommonDialogResult)args.Parameter == CommonDialogResult.Ok)
                    {
                        args.Cancel();
                        args.Session.UpdateContent(new ProgressDialog());
                        var IsSuccessFul = false;
                        var errorMessage = "";
                        try
                        {
                            var statusManager = new StatusManager(((JContent)context.Content).GetJToken().ToObject <Configuration>());
                            var response      = await statusManager.GetStatusAsync();
                            IsSuccessFul      = response.IsSuccessful;
                        }
                        catch (Exception exception)
                        {
                            IsSuccessFul = false;
                            errorMessage = exception is JsonReaderException ? exception.Message : "Failed to connect to selected endpoint!";
                        }
                        finally
                        {
                            if (!IsSuccessFul)
                            {
                                context.ErrorMessage = string.IsNullOrEmpty(errorMessage) ? "Failed to connect to selected endpoint!" : errorMessage;
                                context.ShowError    = true;
                                args.Session.UpdateContent(view);
                            }
                            else
                            {
                                canClose = true;
                                args.Session.Close((CommonDialogResult)args.Parameter);
                            }
                        }
                    }
                });
                if ((CommonDialogResult)result == CommonDialogResult.Ok)
                {
                    var newEndpoint = ((JContent)context.Content).GetJToken().ToObject <ConfigurationWithId>();
                    Endpoints.Add(newEndpoint);
                    GlobalStore.Endpoints = Endpoints.ToList();
                }
            });
            EditCommand = new RelayCommand(async() =>
            {
                if (SelectedIndex < 0)
                {
                    return;
                }
                var isSelectedInUse = Endpoints[SelectedIndex].Equals(GlobalStore.SelectedEndpoint);
                var context         = new CommonDialogViewModel
                {
                    Buttons = ButtonsEnum.OkCancel,
                    Header  = "Create new endpoint",
                    Content = new JContent(new { Endpoints[SelectedIndex].ApiBaseEndpoint, Endpoints[SelectedIndex].ApiSecret, Endpoints[SelectedIndex].ParallelLimit, Endpoints[SelectedIndex].BulkSize })
                };
                var view = new CommonDialog {
                    DataContext = context
                };
                var canClose = false;
                var result   = await _dialogHandler.Show(view, "ConnectDialog",
                                                         async(object sender, DialogClosingEventArgs args) =>
                {
                    if (!canClose && (CommonDialogResult)args.Parameter == CommonDialogResult.Ok)
                    {
                        args.Cancel();
                        args.Session.UpdateContent(new ProgressDialog());
                        var IsSuccessFul = false;
                        try
                        {
                            var statusManager = new StatusManager(((JContent)context.Content).GetJToken().ToObject <Configuration>());
                            var response      = await statusManager.GetStatusAsync();
                            IsSuccessFul      = response.IsSuccessful;
                        }
                        catch (Exception)
                        {
                            IsSuccessFul = false;
                        }
                        finally
                        {
                            if (!IsSuccessFul)
                            {
                                context.ErrorMessage = "Failed to connect to selected endpoint!";
                                context.ShowError    = true;
                                args.Session.UpdateContent(view);
                            }
                            else
                            {
                                canClose = true;
                                args.Session.Close((CommonDialogResult)args.Parameter);
                            }
                        }
                    }
                });
                if ((CommonDialogResult)result == CommonDialogResult.Ok)
                {
                    var modifiedEndpoint     = ((JContent)context.Content).GetJToken().ToObject <ConfigurationWithId>();
                    modifiedEndpoint.Id      = Endpoints[SelectedIndex].Id;
                    Endpoints[SelectedIndex] = modifiedEndpoint;
                    Endpoints             = new ObservableCollection <ConfigurationWithId>(Endpoints);
                    SelectedIndex         = Endpoints.IndexOf(modifiedEndpoint);
                    GlobalStore.Endpoints = Endpoints.ToList();
                    if (isSelectedInUse)
                    {
                        GlobalStore.SelectedEndpoint = Endpoints[SelectedIndex];
                        await((ViewModelLocator)App.Current.Resources["Locator"]).EndpointUpdate();
                        var mainVindow         = new MainWindow();
                        var connectWindow      = App.Current.MainWindow;
                        App.Current.MainWindow = mainVindow;
                        mainVindow.Show();
                        connectWindow.Close();
                    }
                }
            });
            DeleteCommand = new RelayCommand(async() =>
            {
                if (SelectedIndex < 0)
                {
                    return;
                }
                var context = new CommonDialogViewModel
                {
                    Buttons = ButtonsEnum.YesNo,
                    Header  = "Delete endpoint",
                    Content = new Message("Are you sure to delete the selected endpoint?")
                };
                var result = await _dialogHandler.Show(new CommonDialog {
                    DataContext = context
                }, "ConnectDialog");
                if ((CommonDialogResult)result == CommonDialogResult.Yes)
                {
                    Endpoints.RemoveAt(SelectedIndex);
                    SelectedIndex         = 0;
                    GlobalStore.Endpoints = Endpoints.ToList();
                }
            });
        }
 private async void Rename()
 {
     Log.Info(LogMessages.ManageDataSetRenameCommand);
     if (SelectedDataSet == null)
     {
         return;
     }
     var originalName = SelectedDataSet.Name;
     var context      = new CommonDialogViewModel
     {
         Header  = "Rename Dataset",
         Content = new JContent(originalName),
         Buttons = ButtonsEnum.OkCancel
     };
     var view = new CommonDialog {
         DataContext = context
     };
     var canClose = false;
     await _dialogHandler.Show(view, "RootDialog", async (object s, DialogClosingEventArgs args) =>
     {
         if (!canClose && (CommonDialogResult)args.Parameter == CommonDialogResult.Ok)
         {
             args.Cancel();
             args.Session.UpdateContent(new ProgressDialog());
             var isSuccessFul = true;
             var errorMessage = "";
             var newName      = "";
             try
             {
                 newName      = ((JContent)context.Content).GetJToken().ToString();
                 var response = await _dataSetManager.UpdateDataSetAsync(originalName, new DataSetUpdate {
                     Name = newName
                 });
                 ResponseValidator.Validate(response, false);
             }
             catch (Exception exception)
             {
                 isSuccessFul = false;
                 errorMessage = exception.Message;
             }
             finally
             {
                 if (!isSuccessFul)
                 {
                     context.ErrorMessage = errorMessage;
                     context.ShowError    = true;
                     args.Session.UpdateContent(view);
                 }
                 else
                 {
                     var selectedIndex            = DataSets.IndexOf(SelectedDataSet);
                     DataSets[selectedIndex].Name = newName;
                     DataSets = new ObservableCollection <DataSet>(DataSets);
                     Messenger.Default.Send(new UpdateMessage(UpdateType.DatasetRename, originalName));
                     canClose = true;
                     args.Session.Close((CommonDialogResult)args.Parameter);
                 }
             }
         }
     });
 }
        private async Task Add(DataSet selectedDataSet = null)
        {
            Log.Info(LogMessages.ManageDataSetAddCommand);
            var newDataSet = selectedDataSet == null ? new DataSet
            {
                NGramCount        = 3,
                IdField           = "id",
                TagField          = "tag",
                InterpretedFields = new List <string> {
                    "title", "desc"
                },
                SampleDocument = JsonConvert.SerializeObject(new
                {
                    id    = 10,
                    title = "thisisthetitle",
                    desc  = "thisisthedesc",
                    tag   = "tag1"
                }, Formatting.Indented),
                Schema = JsonConvert.SerializeObject(new
                {
                    type       = "object",
                    properties = new
                    {
                        id    = new { type = "integer" },
                        title = new { type = "string" },
                        desc  = new { type = "string" },
                        tag   = new { type = "string" }
                    }
                }, Formatting.Indented)
            } : new DataSet
            {
                NGramCount        = SelectedDataSet.NGramCount,
                IdField           = SelectedDataSet.IdField,
                TagField          = SelectedDataSet.TagField,
                InterpretedFields = SelectedDataSet.InterpretedFields,
                SampleDocument    = SelectedDataSet.SampleDocument ?? JsonConvert.SerializeObject(new
                {
                    id    = 10,
                    title = "thisisthetitle",
                    desc  = "thisisthedesc",
                    tag   = "tag1"
                }, Formatting.Indented),
                Schema = selectedDataSet.Schema ?? JsonConvert.SerializeObject(new
                {
                    type       = "object",
                    properties = new
                    {
                        id    = new { type = "integer" },
                        title = new { type = "string" },
                        desc  = new { type = "string" },
                        tag   = new { type = "string" }
                    }
                }, Formatting.Indented)
            };

            var context = new CommonDialogViewModel
            {
                Header  = "Add Dataset",
                Buttons = ButtonsEnum.OkCancel,
                Content = new NewDataSetWrapper {
                    DataSet = newDataSet, SampleDocumentChecked = true
                }
            };
            var view = new CommonDialog {
                DataContext = context
            };
            var canClose = false;
            var result   = await _dialogHandler.Show(view, "RootDialog",
                                                     async (object sender, DialogClosingEventArgs args) =>
            {
                if (!canClose && (CommonDialogResult)args.Parameter == CommonDialogResult.Ok)
                {
                    args.Cancel();
                    args.Session.UpdateContent(new ProgressDialog());
                    var isSuccessful = false;
                    var errorMessage = "";
                    try
                    {
                        var wrapper = (NewDataSetWrapper)(context.Content);
                        newDataSet  = wrapper.DataSet;
                        if (wrapper.SampleDocumentChecked)
                        {
                            newDataSet.Schema         = null;
                            newDataSet.SampleDocument = JsonConvert.DeserializeObject(newDataSet.SampleDocument.ToString());
                        }
                        else
                        {
                            newDataSet.SampleDocument = null;
                            newDataSet.Schema         = JsonConvert.DeserializeObject((newDataSet.Schema).ToString());
                        }
                        newDataSet.InterpretedFields = newDataSet.InterpretedFields.Where(f => !string.IsNullOrEmpty(f.Trim())).ToList();
                        var response = wrapper.SampleDocumentChecked ? await _dataSetManager.CreateDataSetAsync(newDataSet) : await _dataSetManager.CreateDataSetSchemaAsync(newDataSet);
                        isSuccessful = response.IsSuccessful;
                        ResponseValidator.Validate(response, false);
                    }
                    catch (Exception exception)
                    {
                        isSuccessful = false;
                        errorMessage = exception.Message;
                    }
                    finally
                    {
                        if (!isSuccessful)
                        {
                            context.ErrorMessage = errorMessage;
                            context.ShowError    = true;
                            args.Session.UpdateContent(view);
                        }
                        else
                        {
                            canClose = true;
                            args.Session.Close((CommonDialogResult)args.Parameter);
                        }
                    }
                }
            });

            if ((CommonDialogResult)result == CommonDialogResult.Ok)
            {
                DataSets.Add(newDataSet);
            }
        }