Inheritance: MonoBehaviour
        public AccountsRecivableReportForm(int docID, DateTime startDate, DateTime endDate, Dialogs.AccountsRecivableDialog.updateFormProgress callback)
        {
            InitializeComponent();

            this.docID = docID;
            this.startDate = startDate;
            this.endDate = endDate;
            this.callBack = callback;
        }
Ejemplo n.º 2
0
        public DialogInfo(Dialogs dialogs)
        {
            _dialogs = dialogs;

            DialogCharacters = new ObservableCollection<DialogCharacter>();
            DialogCharacters.CollectionChanged += CharactersCollectionChanged;
            _graph.GraphChanged += OnGraphChanged;

            _attributeCollection = new CharacterAttributeCollection(this);
            _attributeCollection.AddProperty("IsPlayer", typeof (bool));
        }
 public ManualFirmwareSource(Dialogs.IFileSelector FileSelector)
 {
     SelectPackageCommand = new ActionCommand(OpenFirmware);
     OpenFirmware(null);
     _fileSelector = FileSelector;
     FileSelector.Filters =
         new Dictionary<String, String>()
         {
             { "Прошивка блока" , "*." + FirmwarePacking.FirmwarePackage.FirmwarePackageExtension },
             { "Все файлы" , "*.*" }
         };
     FileSelector.DefaultExtension = "*." + FirmwarePacking.FirmwarePackage.FirmwarePackageExtension;
 }
Ejemplo n.º 4
0
 public DialogObjectManager()
 {
     _dialogs = new Dialogs();
 }
Ejemplo n.º 5
0
    void Start()
    {
        GameObject gameOb = GameObject.Find ("Main");

                if (dialogsComponent == null) {
                        if (gameOb != null)
                                dialogsComponent = gameOb.GetComponent<Dialogs> ();
                }

                if (gameComponent == null) {
                        if (gameOb != null)
                                gameComponent = gameOb.GetComponent<Game> ();
                }
    }
Ejemplo n.º 6
0
        public void AddSkills()
        {
            // Simple skill, no slots
            _skillManifests.Add(ManifestUtilities.CreateSkill(
                                    "testskill",
                                    "testskill",
                                    "https://testskill.tempuri.org/api/skill",
                                    "testSkill/testAction"));

            // Simple skill, with one slot (param1)
            var slots = new List <Slot>();

            slots.Add(new Slot {
                Name = "param1", Types = new List <string>()
                {
                    "string"
                }
            });
            _skillManifests.Add(ManifestUtilities.CreateSkill(
                                    "testskillwithslots",
                                    "testskillwithslots",
                                    "https://testskillwithslots.tempuri.org/api/skill",
                                    "testSkill/testActionWithSlots",
                                    slots));

            // Simple skill, with two actions and multiple slots
            var multiParamSlots = new List <Slot>();

            multiParamSlots.Add(new Slot {
                Name = "param1", Types = new List <string>()
                {
                    "string"
                }
            });
            multiParamSlots.Add(new Slot {
                Name = "param2", Types = new List <string>()
                {
                    "string"
                }
            });
            multiParamSlots.Add(new Slot {
                Name = "param3", Types = new List <string>()
                {
                    "string"
                }
            });

            var multiActionSkill = ManifestUtilities.CreateSkill(
                "testskillwithmultipleactionsandslots",
                "testskillwithmultipleactionsandslots",
                "https://testskillwithslots.tempuri.org/api/skill",
                "testSkill/testAction1",
                multiParamSlots);

            multiActionSkill.Actions.Add(ManifestUtilities.CreateAction("testSkill/testAction2", multiParamSlots));
            _skillManifests.Add(multiActionSkill);

            // Each Skill has a number of actions, these actions are added as their own SkillDialog enabling
            // the SkillDialog to know which action is invoked and identify the slots as appropriate.
            foreach (var skill in _skillManifests)
            {
                Dialogs.Add(new SkillDialogTest(skill, _mockServiceClientCredentials, _mockTelemetryClient, UserState, _mockSkillTransport));
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Run every turn of the conversation. Handles orchestration of messages.
        /// </summary>
        /// <param name="turnContext">Bot Turn Context.</param>
        /// <param name="cancellationToken">Task CancellationToken.</param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task OnTurnAsync(ITurnContext turnContext, CancellationToken cancellationToken)
        {
            var activity = turnContext.Activity;

            // Create a dialog context
            var dc = await Dialogs.CreateContextAsync(turnContext);

            if (activity.Type == ActivityTypes.Message)
            {
                // Remove the bot mention to avoid issues with LUIS's NLP
                dc.Context.Activity.RemoveRecipientMention();

                // Perform a call to LUIS to retrieve results for the current activity message.
                var luisResults = await _services.LuisServices[LuisConfiguration].RecognizeAsync(dc.Context, cancellationToken).ConfigureAwait(false);

                // If any entities were updated, treat as interruption.
                // For example, "no my name is tony" will manifest as an update of the name to be "tony".
                var topScoringIntent = luisResults?.GetTopScoringIntent();

                var topIntent = topScoringIntent.Value.intent;

                // update greeting state with any entities captured
                // await UpdateGreetingState(luisResults, dc.Context);

                // Handle conversation interrupts first.
                var interrupted = await IsTurnInterruptedAsync(dc, topIntent);

                if (interrupted)
                {
                    // Bypass the dialog.
                    // Save state before the next turn.
                    await _conversationState.SaveChangesAsync(turnContext);

                    await _userState.SaveChangesAsync(turnContext);

                    return;
                }

                // for testing to view list of jobs. TODO: clean up
                var text = turnContext.Activity.Text.Trim().ToLowerInvariant();
                switch (text)
                {
                case "show":
                case "show jobs":
                    await _jobService.ListJobs(turnContext);

                    break;

                default:
                    break;
                }

                // Continue the current dialog
                var dialogResult = await dc.ContinueDialogAsync();

                // if no one has responded,
                if (!dc.Context.Responded)
                {
                    // examine results from active dialog
                    switch (dialogResult.Status)
                    {
                    case DialogTurnStatus.Empty:
                        switch (topIntent)
                        {
                        case GreetingIntent:
                            await dc.Context.SendActivityAsync("Hello, this is Niles, your DevOps ChatBot assistant");

                            break;

                        case CreateIssueIntent:
                            await dc.BeginDialogAsync(nameof(CreateIssueDialog));

                            break;

                        case NoneIntent:
                        default:
                            // Help or no intent identified, either way, let's provide some help.
                            // to the user
                            await dc.Context.SendActivityAsync("I didn't understand what you just said to me.");
                            await DisplayHelp(dc.Context);

                            break;
                        }

                        break;

                    case DialogTurnStatus.Waiting:
                        // The active dialog is waiting for a response from the user, so do nothing.
                        break;

                    case DialogTurnStatus.Complete:
                        await dc.EndDialogAsync();

                        break;

                    default:
                        await dc.CancelAllDialogsAsync();

                        break;
                    }
                }
            }
            else if (activity.Type == ActivityTypes.ConversationUpdate)
            {
                // Debugging purposes. Remove Later
                await dc.Context.SendActivityAsync("Conversation Update occured");

                if (activity.MembersAdded.Any())
                {
                    // Iterate over all new members added to the conversation.
                    foreach (var member in activity.MembersAdded)
                    {
                        // Debugging purposes. Remove Later
                        await dc.Context.SendActivityAsync($"Member joined {member.Name} with id: {member.Id}");

                        // Greet anyone that was not the target (recipient) of this message.
                        // To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
                        if (member.Id != activity.Recipient.Id)
                        {
                            var welcomeCard = CreateAdaptiveCardAttachment(@".\Dialogs\Welcome\Resources\welcomeCard.json");
                            var response    = CreateResponse(activity, welcomeCard);
                            await dc.Context.SendActivityAsync(response).ConfigureAwait(false);
                        }
                        else
                        {
                            await dc.Context.SendActivityAsync($"Thanks for adding Niles. Type anything to get started.");

                            // save conversation channel
                            await _notificationService.StartChannel(turnContext);
                        }
                    }
                }
            }

            await _conversationState.SaveChangesAsync(turnContext);

            await _userState.SaveChangesAsync(turnContext);
        }
Ejemplo n.º 8
0
        private void DialogClosed(object sender, Coddee.Services.Dialogs.IDialog e)
        {
            var dialog = e as DialogContainerViewModel;

            Dialogs.RemoveIfExists(dialog);
        }
Ejemplo n.º 9
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Abort if some of the required dependencies are missing
            if (Dependencies.AreRequiredBinariesPresent(Constant.VersionUpdates.ApplicationName, Assembly.GetExecutingAssembly()) == false)
            {
                Dialogs.DependencyFilesMissingDialog(Constant.VersionUpdates.ApplicationName);
                Application.Current.Shutdown();
            }

            // Check for updates at least once a day
            if (DateTime.Now.Year != this.State.MostRecentCheckForUpdates.Year ||
                DateTime.Now.Month != this.State.MostRecentCheckForUpdates.Month ||
                DateTime.Now.Day != this.State.MostRecentCheckForUpdates.Day)
            {
                VersionChecks updater = new VersionChecks(this, Constant.VersionUpdates.ApplicationName, Constant.VersionUpdates.LatestVersionFileNameXML);
                updater.TryCheckForNewVersionAndDisplayResultsAsNeeded(false);
                this.State.MostRecentCheckForUpdates = DateTime.Now;
            }
            if (this.State.FirstTimeFileLoading)
            {
                // Load the previously saved layout. If there is none, TryLoad will default to a reasonable layout and window size/position.
                this.AvalonLayout_TryLoad(Constant.AvalonLayoutTags.LastUsed);
                this.State.FirstTimeFileLoading = false;
            }

            if (!SystemStatus.CheckAndGetLangaugeAndCulture(out _, out _, out string displayname))
            {
                this.HelpDocument.WarningRegionLanguage = displayname;
            }

            // Add a context menu to the data controls that allows a user to restore default values to the current or selected file
            // I originally had this in the XAML, but for some reason it complains if put there.
            ContextMenu menuRestoreDefaults = new ContextMenu();
            //{
            //    Name = "MenuRestoreDefaults"
            //};
            MenuItem menuItemRestoreDefaults = new MenuItem();

            //{
            //    Header = "Restore default values for this file",
            //    ToolTip = "Restores the default values for all fields for this file excepting file paths and date/times"
            //};
            menuItemRestoreDefaults.Click += MenuItemRestoreDefaultValues_Click;
            menuRestoreDefaults.Opened    += this.MenuRestoreDefaults_Opened;
            menuRestoreDefaults.Items.Add(menuItemRestoreDefaults);
            this.DataEntryControls.ContextMenu = menuRestoreDefaults;

            if (this.Arguments.IsViewOnly)
            {
                this.State.IsViewOnly = true;
                // Because its readonly, disable the data entry panel, the copy previous values button, the data entry panels' context menu etc.
                // Individual controls are disabled in the DataEntryX panel
                this.DataEntryControls.ContextMenu       = null;
                this.CopyPreviousValuesButton.Visibility = Visibility.Collapsed;
                this.EnableOrDisableMenusAndControls();
            }

            this.DataEntryControlPanel.IsVisible = false;
            this.InstructionPane.IsActive        = true;


            if (false == String.IsNullOrEmpty(this.Arguments.Template))
            {
                if (File.Exists(this.Arguments.Template))
                {
                    Mouse.OverrideCursor = Cursors.Wait;
                    this.StatusBar.SetMessage("Loading images, please wait...");
                    await this.TryOpenTemplateAndBeginLoadFoldersAsync(this.Arguments.Template).ConfigureAwait(true);

                    if (false == String.IsNullOrEmpty(this.Arguments.RelativePath))
                    {
                        // Set and only use the relative path as a search term
                        this.DataHandler.FileDatabase.CustomSelection.ClearCustomSearchUses();
                        this.DataHandler.FileDatabase.CustomSelection.SetAndUseRelativePathSearchTerm(this.Arguments.RelativePath);
                        if (null == this.DataHandler?.ImageCache?.Current)
                        {
                            await this.FilesSelectAndShowAsync(FileSelectionEnum.Folders).ConfigureAwait(true);  // Go to the first result (i.e., index 0) in the given selection set
                        }
                        else
                        {
                            await this.FilesSelectAndShowAsync(this.DataHandler.ImageCache.Current.ID, FileSelectionEnum.Folders).ConfigureAwait(true);  // Go to the first result (i.e., index 0) in the given selection set
                        }
                    }
                    this.StatusBar.SetMessage("Image set is now loaded.");
                    Mouse.OverrideCursor = null;

                    if (this.Arguments.ConstrainToRelativePath)
                    {
                        // Tell user that its a constrained relative path,
                        // Also, set the File menus so that users cannot close and reopen a new image set
                        // This is to avoid confusion as to how the user may mis-interpret the argument state given another image set
                        Dialogs.ArgumentRelativePathDialog(this, this.Arguments.RelativePath);
                        this.MenuItemExit.Header = "Close image set and exit Timelapse";
                        this.MenuFileCloseImageSet.Visibility = Visibility.Collapsed;
                    }
                }
                else
                {
                    // We can't open the template. Show a message and ignore the arguments (by clearing them)
                    Dialogs.ArgumentTemplatePathDialog(this, this.Arguments.Template, this.Arguments.RelativePath);
                    this.Arguments = new DataStructures.Arguments(null);
                }
            }
            if (this.State.IsViewOnly)
            {
                Dialog.Dialogs.OpeningMessageReadOnly(this);
            }
            if (this.State.SuppressOpeningMessageDialog == false)
            {
                Dialogs.OpeningMessage(this);
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="OpenUnavailableProjectMessageElements"/> class and determines the path of the mdi client
 /// </summary>
 public OpenUnavailableProjectMessageElements()
 {
     this.repository = Dialogs.Instance;
 }
Ejemplo n.º 11
0
 public static void MsgBoxResultFirmwareInfo()
 {
     Dialogs.InfoDialog("Firmware Info", "Firmware it's already downloaded! Now the firmware will be extracted it!");
 }
Ejemplo n.º 12
0
 public static void MsgBoxUnzippyAlert()
 {
     Dialogs.InfoDialog("Unzip Engine", @"Please choose a zip file and extraction folder first!");
 }
Ejemplo n.º 13
0
 public static void MSGBOXBootloaderWarning()
 {
     Dialogs.WarningDialog("Bootloader: Warning!", "Device doesn't found, Please plug the phone and check if developer (adb) options are enabled!");
 }
Ejemplo n.º 14
0
 public static void MSGBOXFirmwareMissing()
 {
     Dialogs.WarningDialog("Files Engine: Firmware Missing", "Opss can't find Firmware...");
 }
Ejemplo n.º 15
0
 public static void MSGBOXFileCorrupted()
 {
     Dialogs.WarningDialog("Files Engine: File Corrupted", @"File is corrupted \: Downloading again!");
 }
Ejemplo n.º 16
0
 private void OpenEditor(object dataContext)
 {
     m_EditItem = (IScreen)dataContext;
     Dialogs.ShowDialog(m_EditItem);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="EvaluationInfoElements"/> class and determines the path of the mdi client
 /// </summary>
 public EvaluationInfoElements()
 {
     this.repository = Dialogs.Instance;
 }
Ejemplo n.º 18
0
        public void Init()
        {
            if (IsInit)
            {
                return;
            }

            IsInit = true;

            var lua     = AppApplication.Lua;
            var dialogs = new Dialogs();

            //选择器
            lua["by"]      = new By();
            lua["context"] = AppApplication.Instance.ApplicationContext;
            //app 操作
            lua["app"] = new LuaAppUtils(AppApplication.Instance);
            //设备信息
            lua["device"] = new Device();
            //弹窗
            lua["dialogs"] = dialogs;
            //脚本系统
            lua["engines"] = new Engines();
            //事件系统
            lua["events"] = new Api.Events();
            //文件系统
            lua["files"] = new LuaFiles();
            //网络请求模块
            lua["http"] = new HttpLua();
            //顔色模塊
            lua["colors"] = new Colors();

            luaGlobal = new LuaGlobalMethod(AppApplication.Instance);

            var luaGlobalType = typeof(LuaGlobalMethod);
            var dialogsType   = typeof(Dialogs);

            //加载lua可以调用C#框架函数
            lua.LoadCLRPackage();
            //注册lua全局函数
            lua.RegisterFunction("sleep", luaGlobal, luaGlobalType.GetMethod("Sleep"));
            lua.RegisterFunction("currentPackage", luaGlobal, luaGlobalType.GetMethod("CurrentPackage"));
            lua.RegisterFunction("currentActivity", luaGlobal, luaGlobalType.GetMethod("CurrentActivity"));
            lua.RegisterFunction("setClip", luaGlobal, luaGlobalType.GetMethod("SetClip"));
            lua.RegisterFunction("getClip", luaGlobal, luaGlobalType.GetMethod("GetClip"));
            lua.RegisterFunction("toast", luaGlobal, luaGlobalType.GetMethod("Toast"));
            lua.RegisterFunction("toastLog", luaGlobal, luaGlobalType.GetMethod("ToastLog"));
            lua.RegisterFunction("waitForActivity", luaGlobal, luaGlobalType.GetMethod("WaitForActivity"));
            lua.RegisterFunction("waitForPackage", luaGlobal, luaGlobalType.GetMethod("WaitForPackage"));
            lua.RegisterFunction("exit", luaGlobal, luaGlobalType.GetMethod("Exit"));
            lua.RegisterFunction("print", luaGlobal, luaGlobalType.GetMethod("Print"));
            lua.RegisterFunction("log", luaGlobal, luaGlobalType.GetMethod("Print"));

            //点击
            lua.RegisterFunction("click", luaGlobal, luaGlobalType.GetMethod("Click"));
            lua.RegisterFunction("longClick", luaGlobal, luaGlobalType.GetMethod("LongClick"));
            lua.RegisterFunction("press", luaGlobal, luaGlobalType.GetMethod("Press"));
            lua.RegisterFunction("swipe", luaGlobal, luaGlobalType.GetMethod("Swipe"));
            lua.RegisterFunction("gesture", luaGlobal, luaGlobalType.GetMethod("Gesture"));
            lua.RegisterFunction("gestures", luaGlobal, luaGlobalType.GetMethod("Gestures"));

            //弹窗
            lua.RegisterFunction("alert", dialogsType, dialogsType.GetMethod("alert"));
        }
Ejemplo n.º 19
0
 public static void MSGBOXServerNetworkLost()
 {
     Dialogs.ErrorDialog("Device Server: Network Lost", "Can't connect to server! Please check your internet connection!");
 }
Ejemplo n.º 20
0
        private static void CriarEstruturaDeDados()
        {
            Dialogs.Info(":: " + _addonName + " :: Criando tabelas e estruturas de dados ...");

            try
            {
                _company.StartTransaction();

                var tabela_detalhe_item = new Tabela("U_UPD_CCD1", "Detalhes do item Previsto"
                                                     , SAPbobsCOM.BoUTBTableType.bott_DocumentLines
                                                     , new List <Coluna>()
                {
                    new ColunaVarchar("ItemCode", "Código do Item", 30, true),
                    new ColunaVarchar("ItemName", "Descrição do Item", 120, true),
                    new ColunaPercent("PercItem", "Percentagem Classe", true),
                    new ColunaInt("teste", "teste", true),
                });

                var tabela_contratos = new TabelaUDO("U_UPD_OCCD", "Definições Gerais do Contrato"
                                                     , SAPbobsCOM.BoUTBTableType.bott_Document
                                                     , new List <Coluna>()
                {
                    new ColunaVarchar("CardCode", "Código Fornecedor", 15, true, ""),
                    new ColunaVarchar("CardName", "Descrição Fornecedor", 100, true, ""),
                    new ColunaVarchar("CtName", "Pessoa de Contato", 50, true, ""),
                    new ColunaVarchar("Tel1", "Pessoa de Contato", 15, true, ""),
                    new ColunaVarchar("EMail", "E-mail", 50, true, ""),
                    new ColunaDate("DtPrEnt", "Data Previsão Entrega", true),
                    new ColunaDate("DtPrPgt", "Data Programa Entrega", true),
                    new ColunaInt("ModCtto", "Modalidade Contrato", true),
                    new ColunaInt("teste", "teste", true),
                }
                                                     , new UDOParams()
                {
                    CanDelete = SAPbobsCOM.BoYesNoEnum.tNO
                }
                                                     , new List <Tabela>()
                {
                    tabela_detalhe_item
                }
                                                     );

                //Database.ExcluirColuna(tabela_contratos.NomeComArroba, "teste");


                //var coluna_teste = new ColunaInt("testex", "xtestex", true);
                //Database.CriarColuna(tabela_contratos.NomeComArroba, coluna_teste);
                //Database.DefinirColunasComoUDO(tabela_contratos.NomeComArroba, new List<Coluna>() { coluna_teste });

                //Database.ExcluirTabela(tabela_contratos.NomeSemArroba);

                _company.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_Commit);
            }
            catch (DatabaseException e)
            {
                Dialogs.PopupError(e.Message);
            }
            catch (Exception e)
            {
                _company.EndTransaction(SAPbobsCOM.BoWfTransOpt.wf_RollBack);
                Dialogs.PopupError("Erro interno.\nErro: " + e.Message);
            }
        }
Ejemplo n.º 21
0
        private async Task <DialogTurnResult> RouteStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var activity    = stepContext.Context.Activity.AsMessageActivity();
            var userProfile = await _userProfileState.GetAsync(stepContext.Context, () => new UserProfileState(), cancellationToken);

            if (!string.IsNullOrEmpty(activity.Text))
            {
                // Get current cognitive models for the current locale.
                var localizedServices = _services.GetCognitiveModels();

                // Get dispatch result from turn state.
                var dispatchResult = stepContext.Context.TurnState.Get <DispatchLuis>(StateProperties.DispatchResult);
                (var dispatchIntent, var dispatchScore) = dispatchResult.TopIntent();

                if (IsSkillIntent(dispatchIntent))
                {
                    var dispatchIntentSkill = dispatchIntent.ToString();
                    var skillDialogArgs     = new BeginSkillDialogOptions {
                        Activity = (Activity)activity
                    };

                    // Save active skill in state.
                    var selectedSkill = _skillsConfig.Skills[dispatchIntentSkill];
                    await _activeSkillProperty.SetAsync(stepContext.Context, selectedSkill, cancellationToken);

                    // Start the skill dialog.
                    return(await stepContext.BeginDialogAsync(dispatchIntentSkill, skillDialogArgs, cancellationToken));
                }

                if (dispatchIntent == DispatchLuis.Intent.q_Faq)
                {
                    stepContext.SuppressCompletionMessage(true);

                    var knowledgebaseId = FaqDialogId;
                    var qnaDialog       = TryCreateQnADialog(knowledgebaseId, localizedServices);
                    if (qnaDialog != null)
                    {
                        Dialogs.Add(qnaDialog);
                    }

                    return(await stepContext.BeginDialogAsync(knowledgebaseId, cancellationToken : cancellationToken));
                }

                if (ShouldBeginChitChatDialog(stepContext, dispatchIntent, dispatchScore))
                {
                    stepContext.SuppressCompletionMessage(true);

                    var knowledgebaseId = "Chitchat";
                    var qnaDialog       = TryCreateQnADialog(knowledgebaseId, localizedServices);
                    if (qnaDialog != null)
                    {
                        Dialogs.Add(qnaDialog);
                    }

                    return(await stepContext.BeginDialogAsync(knowledgebaseId, cancellationToken : cancellationToken));
                }

                stepContext.SuppressCompletionMessage(true);

                await stepContext.Context.SendActivityAsync(_templateManager.GenerateActivityForLocale("UnsupportedMessage", userProfile), cancellationToken);

                return(await stepContext.NextAsync(cancellationToken : cancellationToken));
            }

            return(await stepContext.NextAsync(cancellationToken : cancellationToken));
        }
        protected async Task CheckPasswordAsync()
        {
            if (string.IsNullOrWhiteSpace(MasterPasswordCell.TextField.Text))
            {
                var alert = Dialogs.CreateAlert(AppResources.AnErrorHasOccurred,
                                                string.Format(AppResources.ValidationFieldRequired,
                                                              _pinLock ? AppResources.PIN : AppResources.MasterPassword),
                                                AppResources.Ok);
                PresentViewController(alert, true, null);
                return;
            }

            var email = await _stateService.GetEmailAsync();

            var kdf = await _stateService.GetKdfTypeAsync();

            var kdfIterations = await _stateService.GetKdfIterationsAsync();

            var inputtedValue = MasterPasswordCell.TextField.Text;

            if (_pinLock)
            {
                var failed = true;
                try
                {
                    if (_isPinProtected)
                    {
                        var key = await _cryptoService.MakeKeyFromPinAsync(inputtedValue, email,
                                                                           kdf.GetValueOrDefault(KdfType.PBKDF2_SHA256), kdfIterations.GetValueOrDefault(5000),
                                                                           await _stateService.GetPinProtectedKeyAsync());

                        var encKey = await _cryptoService.GetEncKeyAsync(key);

                        var protectedPin = await _stateService.GetProtectedPinAsync();

                        var decPin = await _cryptoService.DecryptToUtf8Async(new EncString(protectedPin), encKey);

                        failed = decPin != inputtedValue;
                        if (!failed)
                        {
                            await AppHelpers.ResetInvalidUnlockAttemptsAsync();
                            await SetKeyAndContinueAsync(key);
                        }
                    }
                    else
                    {
                        var key2 = await _cryptoService.MakeKeyFromPinAsync(inputtedValue, email,
                                                                            kdf.GetValueOrDefault(KdfType.PBKDF2_SHA256), kdfIterations.GetValueOrDefault(5000));

                        failed = false;
                        await AppHelpers.ResetInvalidUnlockAttemptsAsync();
                        await SetKeyAndContinueAsync(key2);
                    }
                }
                catch
                {
                    failed = true;
                }
                if (failed)
                {
                    await HandleFailedCredentialsAsync();
                }
            }
            else
            {
                var key2 = await _cryptoService.MakeKeyAsync(inputtedValue, email, kdf, kdfIterations);

                var storedKeyHash = await _cryptoService.GetKeyHashAsync();

                if (storedKeyHash == null)
                {
                    var oldKey = await _secureStorageService.GetAsync <string>("oldKey");

                    if (key2.KeyB64 == oldKey)
                    {
                        var localKeyHash = await _cryptoService.HashPasswordAsync(inputtedValue, key2, HashPurpose.LocalAuthorization);

                        await _secureStorageService.RemoveAsync("oldKey");

                        await _cryptoService.SetKeyHashAsync(localKeyHash);
                    }
                }
                var passwordValid = await _cryptoService.CompareAndUpdateKeyHashAsync(inputtedValue, key2);

                if (passwordValid)
                {
                    if (_isPinProtected)
                    {
                        var protectedPin = await _stateService.GetProtectedPinAsync();

                        var encKey = await _cryptoService.GetEncKeyAsync(key2);

                        var decPin = await _cryptoService.DecryptToUtf8Async(new EncString(protectedPin), encKey);

                        var pinKey = await _cryptoService.MakePinKeyAysnc(decPin, email,
                                                                          kdf.GetValueOrDefault(KdfType.PBKDF2_SHA256), kdfIterations.GetValueOrDefault(5000));

                        await _stateService.SetPinProtectedKeyAsync(await _cryptoService.EncryptAsync(key2.Key, pinKey));
                    }
                    await AppHelpers.ResetInvalidUnlockAttemptsAsync();
                    await SetKeyAndContinueAsync(key2, true);
                }
                else
                {
                    await HandleFailedCredentialsAsync();
                }
            }
        }
Ejemplo n.º 23
0
            public async override void RowSelected(UITableView tableView, NSIndexPath indexPath)
            {
                tableView.DeselectRow(indexPath, true);
                tableView.EndEditing(true);

                if (Items == null || Items.Count() == 0)
                {
                    _controller.PerformSegue("loginAddSegue", this);
                    return;
                }

                var item = Items.ElementAt(indexPath.Row);

                if (item == null)
                {
                    _controller.LoadingController.CompleteRequest(null, null);
                    return;
                }

                if (item.Reprompt != Bit.Core.Enums.CipherRepromptType.None && !await _controller.PasswordRepromptService.ShowPasswordPromptAsync())
                {
                    return;
                }

                if (_controller.CanAutoFill() && !string.IsNullOrWhiteSpace(item.Password))
                {
                    string totp            = null;
                    var    disableTotpCopy = _stateService.GetDisableAutoTotpCopyAsync().GetAwaiter().GetResult();
                    if (!disableTotpCopy.GetValueOrDefault(false))
                    {
                        totp = GetTotpAsync(item).GetAwaiter().GetResult();
                    }
                    _controller.LoadingController.CompleteUsernamePasswordRequest(
                        item.Id, item.Username, item.Password, item.Fields, totp);
                }
                else if (!string.IsNullOrWhiteSpace(item.Username) || !string.IsNullOrWhiteSpace(item.Password) ||
                         !string.IsNullOrWhiteSpace(item.Totp))
                {
                    var sheet = Dialogs.CreateActionSheet(item.Name, _controller);
                    if (!string.IsNullOrWhiteSpace(item.Username))
                    {
                        sheet.AddAction(UIAlertAction.Create(AppResources.CopyUsername, UIAlertActionStyle.Default, a =>
                        {
                            UIPasteboard clipboard = UIPasteboard.General;
                            clipboard.String       = item.Username;
                            var alert = Dialogs.CreateMessageAlert(AppResources.CopyUsername);
                            _controller.PresentViewController(alert, true, () =>
                            {
                                _controller.DismissViewController(true, null);
                            });
                        }));
                    }
                    if (!string.IsNullOrWhiteSpace(item.Password))
                    {
                        sheet.AddAction(UIAlertAction.Create(AppResources.CopyPassword, UIAlertActionStyle.Default, a =>
                        {
                            UIPasteboard clipboard = UIPasteboard.General;
                            clipboard.String       = item.Password;
                            var alert = Dialogs.CreateMessageAlert(
                                string.Format(AppResources.ValueHasBeenCopied, AppResources.Password));
                            _controller.PresentViewController(alert, true, () =>
                            {
                                _controller.DismissViewController(true, null);
                            });
                        }));
                    }
                    if (!string.IsNullOrWhiteSpace(item.Totp))
                    {
                        sheet.AddAction(UIAlertAction.Create(AppResources.CopyTotp, UIAlertActionStyle.Default,
                                                             async a =>
                        {
                            var totp = await GetTotpAsync(item);
                            if (string.IsNullOrWhiteSpace(totp))
                            {
                                return;
                            }
                            UIPasteboard clipboard = UIPasteboard.General;
                            clipboard.String       = totp;
                            var alert = Dialogs.CreateMessageAlert(
                                string.Format(AppResources.ValueHasBeenCopied, AppResources.VerificationCodeTotp));
                            _controller.PresentViewController(alert, true, () =>
                            {
                                _controller.DismissViewController(true, null);
                            });
                        }));
                    }
                    sheet.AddAction(UIAlertAction.Create(AppResources.Cancel, UIAlertActionStyle.Cancel, null));
                    _controller.PresentViewController(sheet, true, null);
                }
                else
                {
                    var alert = Dialogs.CreateAlert(null, AppResources.NoUsernamePasswordConfigured, AppResources.Ok);
                    _controller.PresentViewController(alert, true, null);
                }
            }
 /// <summary>
 /// Initializes a new instance of the <see cref="WriteToDeviceWarningMessageElements"/> class and determines the path of the mdi client
 /// </summary>
 public WriteToDeviceWarningMessageElements()
 {
     this.repository = Dialogs.Instance;
 }
Ejemplo n.º 25
0
        public override void OnAfterFormVisible(string FormUID, ref ItemEvent pVal, out bool BubbleEvent)
        {
            base.OnAfterFormVisible(FormUID, ref pVal, out BubbleEvent);

            using (var formCOM = new FormCOM(FormUID))
            {
                var form = formCOM.Form;
                DesabilitarMenuAdicionarNovo(form);

                form.Items.Item(_botaoComboCopiar.ItemUID).AffectsFormMode = false;
                var botaoComboCopiar = (ButtonCombo)form.Items.Item(_botaoComboCopiar.ItemUID).Specific;
                _botaoComboCopiar.Popular(botaoComboCopiar.ValidValues);

                var mtx = GetMatrix(form, _matrizDocumentos.ItemUID);
                _matrizDocumentos.Bind(mtx);

                if (form.Mode == BoFormMode.fm_ADD_MODE)
                {
                    Dialogs.Success("Carregando informações do Contrato de Compra Geral... Aguarde...", BoMessageTime.bmt_Long);

                    using (var fatherFormCOM = new FormCOM(_fatherFormUID))

                        using (var dbdtsCFCOM = new DBDatasourceCOM(form, MainDbDataSource))
                            using (var dbdtsPCCOM = new DBDatasourceCOM(_fatherFormUID, new TabelaPreContrato().NomeComArroba))

                                using (var dbdtsCFCertificadoCOM = new DBDatasourceCOM(form, new TabelaCertificadosDoContratoFinal().NomeComArroba))
                                    using (var dbdtsPCCertificadoCOM = new DBDatasourceCOM(_fatherFormUID, new TabelaCertificadosDoPreContrato().NomeComArroba))

                                        using (var dbdtsCFResponsavelCOM = new DBDatasourceCOM(form, new TabelaResponsaveisDoContratoFinal().NomeComArroba))
                                            using (var dbdtsPCResponsavelCOM = new DBDatasourceCOM(_fatherFormUID, new TabelaResponsaveisDoPreContrato().NomeComArroba))

                                                using (var dbdtsCFCorretorCOM = new DBDatasourceCOM(form, new TabelaCorretoresDoContratoFinal().NomeComArroba))
                                                    using (var dbdtsPCCorretorCOM = new DBDatasourceCOM(_fatherFormUID, new TabelaCorretoresDoPreContrato().NomeComArroba))
                                                    {
                                                        var fatherForm = fatherFormCOM.Form;

                                                        var dbdtsCF = dbdtsCFCOM.Dbdts;
                                                        var dbdtsPC = dbdtsPCCOM.Dbdts;

                                                        var dbdtsCFCertificado = dbdtsCFCertificadoCOM.Dbdts;
                                                        var dbdtsPCCertificado = dbdtsPCCertificadoCOM.Dbdts;

                                                        var dbdtsCFResponsavel = dbdtsCFResponsavelCOM.Dbdts;
                                                        var dbdtsPCResponsavel = dbdtsPCResponsavelCOM.Dbdts;

                                                        var dbdtsCFCorretor = dbdtsCFCorretorCOM.Dbdts;
                                                        var dbdtsPCCorretor = dbdtsPCCorretorCOM.Dbdts;

                                                        try
                                                        {
                                                            form.Freeze(true);

                                                            var labelsIn = string.Empty;
                                                            for (int i = 0; i < _peneiras.Count; i++)
                                                            {
                                                                labelsIn += ",'" + _peneiras[i].Datasource.Replace("P", "L") + "'";
                                                            }

                                                            CopyIfFieldsMatch(dbdtsPC, ref dbdtsCF, labelsIn);
                                                            CopyIfFieldsMatch(dbdtsPCCertificado, ref dbdtsCFCertificado);
                                                            CopyIfFieldsMatch(dbdtsPCResponsavel, ref dbdtsCFResponsavel);
                                                            CopyIfFieldsMatch(dbdtsPCCorretor, ref dbdtsCFCorretor);

                                                            var saldoSacas = Helpers.ToDouble(dbdtsPC.GetValue(_saldoDeSacas.Datasource, 0));
                                                            var saldoPeso  = Helpers.ToDouble(dbdtsPC.GetValue(_saldoDePeso.Datasource, 0));

                                                            saldoSacas = saldoSacas < 0 ? 0 : saldoSacas;
                                                            saldoPeso  = saldoPeso < 0 ? 0 : saldoPeso;

                                                            _quantidadeDeSacas.SetValorDBDatasource(dbdtsCF, saldoSacas);
                                                            _quantidadeDePeso.SetValorDBDatasource(dbdtsCF, saldoPeso);

                                                            CalcularTotais(form, dbdtsCF);

                                                            _OnAdicionarNovo(form);

                                                            PopularPessoasDeContato(form, dbdtsPC.GetValue(_codigoPN.Datasource, 0), dbdtsPC.GetValue(_pessoasDeContato.Datasource, 0));
                                                            HabilitarCamposDePeneira(form, dbdtsCF, dbdtsCF.GetValue(_codigoItem.Datasource, 0));
                                                        }
                                                        finally
                                                        {
                                                            form.Freeze(false);
                                                        }

                                                        Dialogs.Success("Ok.");
                                                    }
                }
            }
        }
Ejemplo n.º 26
0
 public GameAI(Duel duel, string dialog, System.Action <string, bool> chat, System.Action <string, int> log)
 {
     Duel     = duel;
     _log     = log;
     _dialogs = new Dialogs(dialog, chat);
 }
Ejemplo n.º 27
0
        public void DisplayAlert(string title, string message, string accept)
        {
            var alert = Dialogs.CreateAlert(title, message, accept);

            PresentViewController(alert, true, null);
        }
 public virtual Commands.Result RunScript(RhinoDoc doc, RhinoObject[] objectList)
 {
     RhinoApp.WriteLine(Localization.LocalizeString("Scripting not supported for this option", 30));
     Dialogs.ShowMessage(Localization.LocalizeString("Scripting not supported for this option", 31), Localization.LocalizeString("Unsupported Option", 32));
     return(Commands.Result.Success);
 }
Ejemplo n.º 29
0
        private void OnRootDirectoryChanged()
        {
            _directoryDialogMapping.Clear();
            _dialogs = new Dialogs();

            HasChanges = false;
            var action = RootDirectoryChanged;
            if (action != null)
                action();
        }
Ejemplo n.º 30
0
        protected override Result RunCommand(RhinoDoc doc, RunMode mode)
        {
            if (TimePanel.Instance.Restarted && TimePanel.Instance.TrackbarValue == 0)
            {
                ObjRef[] objrefs;
                Result   rc = Rhino.Input.RhinoGet.GetMultipleObjects("Select the polysurfaces for the union",
                                                                      false, ObjectType.Brep, out objrefs);
                if (rc != Result.Success)
                {
                    return(rc);
                }
                if (objrefs == null || objrefs.Length <= 1)
                {
                    Dialogs.ShowMessage("You have to select 2 or more shapes.", "Warning", ShowMessageButton.OK, ShowMessageIcon.Warning);
                    return(Result.Failure);
                }


                List <Brep> in_breps0 = new List <Brep>();
                for (int i = 0; i < objrefs.Length; i++)
                {
                    int index = RigidBodyManager.GuidList.IndexOf(objrefs[i].ObjectId);
                    //Avoid to create a compound from another compound
                    if (RigidBodyManager.RigidBodies[index].Shape is CompoundShape)
                    {
                        Dialogs.ShowMessage("You cannot create compound shape from another compound shape. Try to create it at once.", "Warning", ShowMessageButton.OK, ShowMessageIcon.Warning);
                        return(Result.Failure);
                    }
                    //Accept shapes only if they intersect to each other
                    Brep brep = objrefs[i].Brep();
                    if (brep != null)
                    {
                        in_breps0.Add(brep);
                    }
                    RhinoDoc.ActiveDoc.Objects.Delete(objrefs[i], true);
                }

                //Create the rhino compound shape
                double tolerance = doc.ModelAbsoluteTolerance;
                Brep[] breps     = Brep.CreateBooleanUnion(in_breps0, tolerance);
                if (breps.Length > 1)
                {
                    Dialogs.ShowMessage("You cannot create more than a compound shape in once time.", "Warning", ShowMessageButton.OK, ShowMessageIcon.Warning);
                    return(Result.Failure);
                }

                Brep rhinoCompound = breps[0];
                // If the user create zero or more than 1 compound the command fails
                if (breps.Length != 1)
                {
                    return(Rhino.Commands.Result.Nothing);
                }

                Brep copyToAdd = rhinoCompound.DuplicateBrep();

                //Create the rigid compound shape
                CompoundShape.TransformedShape[] transformedShapes = new CompoundShape.TransformedShape[in_breps0.Count];

                for (int i = 0; i < in_breps0.Count; i++)
                {
                    Guid guid           = objrefs[i].ObjectId;
                    int  indexRigidBody = RigidBodyManager.GuidList.IndexOf(guid);
                    transformedShapes[i] = new CompoundShape.TransformedShape(RigidBodyManager.RigidBodies[indexRigidBody].Shape, RigidBodyManager.RigidBodies[indexRigidBody].Orientation, RigidBodyManager.RigidBodies[indexRigidBody].Position);
                }
                CompoundShape jCompound     = new CompoundShape(transformedShapes);
                RigidBody     jCompoundBody = new RigidBody(jCompound);

                //Move the center of mass of Jitter shape on the center of the BBox of rhino shape
                Point3d centerBbox = rhinoCompound.GetBoundingBox(true).Center;
                jCompoundBody.Position = RigidBodyManager.Point3dtoJVector(centerBbox);
                //Find the difference between rhino bbx center and jitter bbox center
                JVector bboxjitter = jCompoundBody.BoundingBox.Center;
                JVector diff       = bboxjitter - RigidBodyManager.Point3dtoJVector(centerBbox);
                //Align the center of both bboxes
                jCompoundBody.Position -= diff;

                //Translate the center of the Bbox to 0,0,0 and save it to geometry list
                Point3d bboxDoc = rhinoCompound.GetBoundingBox(true).Center;
                rhinoCompound.Translate(new Vector3d(-bboxDoc.X, -bboxDoc.Y, -bboxDoc.Z));

                RigidBodyManager.RigidBodies.Add(jCompoundBody);
                RigidBodyManager.GeometryList.Add(rhinoCompound);
                Guid guidToAdd = doc.Objects.Add(copyToAdd);
                RigidBodyManager.GuidList.Add(guidToAdd);

                doc.Views.Redraw();

                return(Result.Success);
            }
            else
            {
                Dialogs.ShowMessage("Press Restart before use other commands", "Warning", ShowMessageButton.OK, ShowMessageIcon.Warning);
                return(Result.Success);
            }
        }
        private async Task <string> CopyFiles(string path)
        {
            string fileNamePrefix;
            string sourceFile;
            string destFile;
            int    totalFiles           = FileDatabase.FileTable.RowCount;
            int    copiedFiles          = 0;
            int    skippedFiles         = 0;
            int    existingFiles        = 0;
            bool   cancelled            = false;
            bool   renameFileWithPrefix = this.CBRename.IsChecked == true;

            // We first check all files to see if they exist in the destination.
            // Yes, this is a bit heavyweight. There is likely a more efficient way to do this.
            foreach (ImageRow ir in FileDatabase.FileTable)
            {
                fileNamePrefix = renameFileWithPrefix
                ? ir.RelativePath.Replace('\\', '.')
                : String.Empty;

                sourceFile = Path.Combine(FileDatabase.FolderPath, ir.RelativePath, ir.File);
                destFile   = String.IsNullOrWhiteSpace(fileNamePrefix)
                ? Path.Combine(path, fileNamePrefix + ir.File)
                : Path.Combine(path, fileNamePrefix + '.' + ir.File);

                if (File.Exists(destFile))
                {
                    existingFiles++;
                }
            }
            if (existingFiles > 0)
            {
                if (Dialogs.OverwriteExistingFiles(this, existingFiles) != true)
                {
                    copiedFiles = -2; // indicates the duplicate file condition
                    return(String.Format("Export aborted to avoid overwriting files."));
                }
            }

            await Task.Run(() =>
            {
                if (!renameFileWithPrefix)
                {
                    // Since we are not renaming files, we have to check for duplicates.
                    // If even one duplicate exists, abort.
                    HashSet <string> testForDuplicates = new HashSet <string>();
                    foreach (ImageRow ir in FileDatabase.FileTable)
                    {
                        if (!testForDuplicates.Add(ir.File))
                        {
                            cancelled   = true;
                            copiedFiles = -1; // indicates the duplicate file condition
                            return;
                        }
                    }
                }

                foreach (ImageRow ir in FileDatabase.FileTable)
                {
                    if (this.TokenSource.IsCancellationRequested)
                    {
                        cancelled = true;
                        return;
                    }

                    fileNamePrefix = renameFileWithPrefix
                    ? ir.RelativePath.Replace('\\', '.')
                    : String.Empty;

                    sourceFile = Path.Combine(FileDatabase.FolderPath, ir.RelativePath, ir.File);
                    destFile   = String.IsNullOrWhiteSpace(fileNamePrefix)
                    ? Path.Combine(path, fileNamePrefix + ir.File)
                    : Path.Combine(path, fileNamePrefix + '.' + ir.File);

                    try
                    {
                        File.Copy(sourceFile, destFile, true);
                        copiedFiles++;
                    }
                    catch
                    {
                        skippedFiles++;
                    }
                    if (this.ReadyToRefresh())
                    {
                        int percentDone = Convert.ToInt32((copiedFiles + skippedFiles) / Convert.ToDouble(totalFiles) * 100.0);
                        this.Progress.Report(new ProgressBarArguments(percentDone, String.Format("Copying {0} / {1} files", copiedFiles, totalFiles), true, false));
                        Thread.Sleep(Constant.ThrottleValues.RenderingBackoffTime);
                    }
                }
            }).ConfigureAwait(true);

            if (cancelled)
            {
                if (copiedFiles >= 0)
                {
                    return(String.Format("Export cancelled after copying {0} files", copiedFiles));
                }
                else if (copiedFiles == -1)
                {
                    return(String.Format("Export aborted, as duplicate file names exist." + Environment.NewLine + "Try using the Rename option to guarantee unique file names."));
                }
            }
            if (skippedFiles == 0)
            {
                return(String.Format("Copied {0} out of {1} files{2}", copiedFiles, totalFiles, Environment.NewLine));
            }
            string feedbackMessage = String.Format("Copied {0} out of {1} files{2}", copiedFiles, totalFiles, Environment.NewLine);

            feedbackMessage += (skippedFiles == 1)
                    ? String.Format("Skipped {0} file (perhaps it is missing?)", skippedFiles)
                    : String.Format("Skipped {0} files (perhaps they are missing?)", skippedFiles);
            return(feedbackMessage);
        }
Ejemplo n.º 32
0
        async partial void SaveBarButton_Activated(UIBarButtonItem sender)
        {
            if (!_connectivity.IsConnected)
            {
                AlertNoConnection();
                return;
            }

            if (string.IsNullOrWhiteSpace(PasswordCell.TextField.Text))
            {
                DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.Password), AppResources.Ok);
                return;
            }

            if (string.IsNullOrWhiteSpace(NameCell.TextField.Text))
            {
                DisplayAlert(AppResources.AnErrorHasOccurred, string.Format(AppResources.ValidationFieldRequired, AppResources.Name), AppResources.Ok);
                return;
            }

            var cipher = new Cipher
            {
                Name     = string.IsNullOrWhiteSpace(NameCell.TextField.Text) ? null : NameCell.TextField.Text.Encrypt(),
                Notes    = string.IsNullOrWhiteSpace(NotesCell.TextView.Text) ? null : NotesCell.TextView.Text.Encrypt(),
                Favorite = FavoriteCell.Switch.On,
                FolderId = FolderCell.SelectedIndex == 0 ? null : _folders.ElementAtOrDefault(FolderCell.SelectedIndex - 1)?.Id,
                Type     = App.Enums.CipherType.Login,
                Login    = new Login
                {
                    Uris     = null,
                    Username = string.IsNullOrWhiteSpace(UsernameCell.TextField.Text) ? null : UsernameCell.TextField.Text.Encrypt(),
                    Password = string.IsNullOrWhiteSpace(PasswordCell.TextField.Text) ? null : PasswordCell.TextField.Text.Encrypt()
                }
            };

            if (!string.IsNullOrWhiteSpace(UriCell.TextField.Text))
            {
                cipher.Login.Uris = new List <LoginUri>
                {
                    new LoginUri
                    {
                        Uri = UriCell.TextField.Text.Encrypt()
                    }
                };
            }

            var saveTask     = _cipherService.SaveAsync(cipher);
            var loadingAlert = Dialogs.CreateLoadingAlert(AppResources.Saving);

            PresentViewController(loadingAlert, true, null);
            await saveTask;

            await loadingAlert.DismissViewControllerAsync(true);

            if (saveTask.Result.Succeeded)
            {
                _googleAnalyticsService.TrackExtensionEvent("CreatedLogin");
                if (LoginListController != null)
                {
                    LoginListController.DismissModal();
                }
                else if (LoadingController != null)
                {
                    LoadingController.CompleteUsernamePasswordRequest(UsernameCell.TextField.Text, PasswordCell.TextField.Text,
                                                                      null, null);
                }
            }
            else if (saveTask.Result.Errors.Count() > 0)
            {
                DisplayAlert(AppResources.AnErrorHasOccurred, saveTask.Result.Errors.First().Message, AppResources.Ok);
            }
            else
            {
                DisplayAlert(null, AppResources.AnErrorHasOccurred, AppResources.Ok);
            }
        }
Ejemplo n.º 33
0
        // Delete callback manages all deletion menu choices where:
        // - the current image or all images marked for deletion are deleted
        // - the data associated with those images may be delted.
        // - deleted images are moved to a backup folder.
        private async void MenuItemDeleteFiles_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;

            // This callback is invoked by DeleteImage (which deletes the current image) and DeleteImages (which deletes the images marked by the deletion flag)
            // Thus we need to use two different methods to construct a table containing all the images marked for deletion
            List <ImageRow> filesToDelete;
            bool            deleteCurrentImageOnly;
            bool            deleteFilesAndData;

            if (menuItem.Name.Equals(this.MenuItemDeleteFiles.Name) || menuItem.Name.Equals(this.MenuItemDeleteFilesAndData.Name))
            {
                deleteCurrentImageOnly = false;
                deleteFilesAndData     = menuItem.Name.Equals(this.MenuItemDeleteFilesAndData.Name);
                // get list of all images marked for deletion in the current seletion
                using (FileTable filetable = this.DataHandler.FileDatabase.SelectFilesMarkedForDeletion())
                {
                    filesToDelete = filetable.ToList();
                }

                for (int index = filesToDelete.Count - 1; index >= 0; index--)
                {
                    if (this.DataHandler.FileDatabase.FileTable.Find(filesToDelete[index].ID) == null)
                    {
                        filesToDelete.Remove(filesToDelete[index]);
                    }
                }
            }
            else
            {
                // Delete current image case. Get the ID of the current image and construct a datatable that contains that image's datarow
                deleteCurrentImageOnly = true;
                deleteFilesAndData     = menuItem.Name.Equals(this.MenuItemDeleteCurrentFileAndData.Name);
                filesToDelete          = new List <ImageRow>();
                if (this.DataHandler.ImageCache.Current != null)
                {
                    filesToDelete.Add(this.DataHandler.ImageCache.Current);
                }
            }

            // If no images are selected for deletion. Warn the user.
            // Note that this should never happen, as the invoking menu item should be disabled (and thus not selectable)
            // if there aren't any images to delete. Still,...
            if (filesToDelete == null || filesToDelete.Count < 1)
            {
                Dialogs.MenuEditNoFilesMarkedForDeletionDialog(this);
                return;
            }
            long         currentFileID      = this.DataHandler.ImageCache.Current.ID;
            DeleteImages deleteImagesDialog = new DeleteImages(this, this.DataHandler.FileDatabase, this.DataHandler.ImageCache, filesToDelete, deleteFilesAndData, deleteCurrentImageOnly);
            bool?        result             = deleteImagesDialog.ShowDialog();

            if (result == true)
            {
                // Delete the files
                Mouse.OverrideCursor = Cursors.Wait;
                // Reload the file datatable.
                await this.FilesSelectAndShowAsync(currentFileID, this.DataHandler.FileDatabase.ImageSet.FileSelection).ConfigureAwait(true);

                if (deleteFilesAndData)
                {
                    // Find and show the image closest to the last one shown
                    if (this.DataHandler.FileDatabase.CountAllCurrentlySelectedFiles > 0)
                    {
                        int nextImageRow = this.DataHandler.FileDatabase.GetFileOrNextFileIndex(currentFileID);
                        this.FileShow(nextImageRow);
                    }
                    else
                    {
                        // No images left, so disable everything
                        this.EnableOrDisableMenusAndControls();
                    }
                }
                else
                {
                    // display the updated properties on the current image, or the closest one to it.
                    int nextImageRow = this.DataHandler.FileDatabase.FindClosestImageRow(currentFileID);
                    this.FileShow(nextImageRow);
                }
                Mouse.OverrideCursor = null;
            }
        }
Ejemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WriteToDeviceSuccessMessageElements"/> class and determines the path of the mdi client
 /// </summary>
 public WriteToDeviceSuccessMessageElements()
 {
     this.repository = Dialogs.Instance;
 }
Ejemplo n.º 35
0
        //Try to find a missing image
        private async void MenuItemEditFindMissingImage_Click(object sender, RoutedEventArgs e)
        {
            // Don't do anything if the image actually exists. This should not fire, as this menu item is only enabled
            // if there is a current image that doesn't exist. But just in case...
            if (null == this.DataHandler?.ImageCache?.Current || File.Exists(FilesFolders.GetFullPath(this.DataHandler.FileDatabase.FolderPath, this.DataHandler?.ImageCache?.Current)))
            {
                return;
            }

            string   folderPath   = this.DataHandler.FileDatabase.FolderPath;
            ImageRow currentImage = this.DataHandler?.ImageCache?.Current;

            // Search for - and return as list of relative path / filename tuples -  all folders under the root folder for files with the same name as the fileName.
            List <Tuple <string, string> > matchingRelativePathFileNameList = Util.FilesFolders.SearchForFoldersContainingFileName(folderPath, currentImage.File);

            // Remove any of the tuples that are spoken for i.e., that are already associated with a row in the database
            for (int i = matchingRelativePathFileNameList.Count - 1; i >= 0; i--)
            {
                if (this.DataHandler.FileDatabase.ExistsRelativePathAndFileInDataTable(matchingRelativePathFileNameList[i].Item1, matchingRelativePathFileNameList[i].Item2))
                {
                    // We only want matching files that are not already assigned to another datafield in the database
                    matchingRelativePathFileNameList.RemoveAt(i);
                }
            }

            // If there are no remaining tuples, it means no potential matches were found.
            // Display a message saying so and abort.
            if (matchingRelativePathFileNameList.Count == 0)
            {
                Dialogs.MissingFileSearchNoMatchesFoundDialog(this, currentImage.File);
                return;
            }

            // Now retrieve a list of all filenames located in the same folder (i.e., that have the same relative path) as the missing file.
            List <string> otherMissingFiles = this.DataHandler.FileDatabase.SelectFileNamesWithRelativePathFromDatabase(currentImage.RelativePath);

            // Remove the current missing file from the list, as well as any file that exists i.e., that is not missing.
            for (int i = otherMissingFiles.Count - 1; i >= 0; i--)
            {
                if (String.Equals(otherMissingFiles[i], currentImage.File) || File.Exists(Path.Combine(folderPath, currentImage.RelativePath, otherMissingFiles[i])))
                {
                    otherMissingFiles.RemoveAt(i);
                }
            }

            // For those that are left (if any), see if other files in the returned locations are in each path. Get their count, save them, and pass the count as a parameter e.g., a Dict with matching files, etc.
            // Or perhapse even better, a list of file names for each path Dict<string, List<string>>
            // As we did above, go through the other missing files and remove those that are spoken for i.e., that are already associated with a row in the database.
            // What remains will be a list of  root paths, each with a list of  missing (unassociated) files that could be candidates for locating
            Dictionary <string, List <string> > otherMissingFileCandidates = new Dictionary <string, List <string> >();

            foreach (Tuple <string, string> matchingPath in matchingRelativePathFileNameList)
            {
                List <string> orphanMissingFiles = new List <string>();
                foreach (string otherMissingFile in otherMissingFiles)
                {
                    // Its a potential candidate if its not already referenced but it exists in that relative path folder
                    if (false == this.DataHandler.FileDatabase.ExistsRelativePathAndFileInDataTable(matchingPath.Item1, otherMissingFile) &&
                        File.Exists(FilesFolders.GetFullPath(FolderPath, matchingPath.Item1, otherMissingFile)))
                    {
                        orphanMissingFiles.Add(otherMissingFile);
                    }
                }
                otherMissingFileCandidates.Add(matchingPath.Item1, orphanMissingFiles);
            }

            Dialog.MissingImageLocateRelativePaths dialog = new Dialog.MissingImageLocateRelativePaths(this, this.DataHandler.FileDatabase, currentImage.RelativePath, currentImage.File, otherMissingFileCandidates);

            bool?result = dialog.ShowDialog();

            if (result == true)
            {
                Tuple <string, string> locatedMissingFile = dialog.LocatedMissingFile;
                if (String.IsNullOrEmpty(locatedMissingFile.Item2))
                {
                    return;
                }

                // Update the original missing file
                List <ColumnTuplesWithWhere> columnTuplesWithWhereList = new List <ColumnTuplesWithWhere>();
                ColumnTuplesWithWhere        columnTuplesWithWhere     = new ColumnTuplesWithWhere();
                columnTuplesWithWhere.Columns.Add(new ColumnTuple(Constant.DatabaseColumn.RelativePath, locatedMissingFile.Item1)); // The new relative path
                columnTuplesWithWhere.SetWhere(currentImage.RelativePath, currentImage.File);                                       // Where the original relative path/file terms are met
                columnTuplesWithWhereList.Add(columnTuplesWithWhere);

                // Update the other missing files in the database, if any
                foreach (string otherMissingFileName in otherMissingFileCandidates[locatedMissingFile.Item1])
                {
                    columnTuplesWithWhere = new ColumnTuplesWithWhere();
                    columnTuplesWithWhere.Columns.Add(new ColumnTuple(Constant.DatabaseColumn.RelativePath, locatedMissingFile.Item1)); // The new value
                    columnTuplesWithWhere.SetWhere(currentImage.RelativePath, otherMissingFileName);                                    // Where the original relative path/file terms are met
                    columnTuplesWithWhereList.Add(columnTuplesWithWhere);
                }

                // Now update the database
                this.DataHandler.FileDatabase.UpdateFiles(columnTuplesWithWhereList);
                await this.FilesSelectAndShowAsync().ConfigureAwait(true);
            }
        }
 public IEnumerable <Dialog> GetDependencies()
 {
     return(Dialogs.GetDialogs());
 }
Ejemplo n.º 37
0
 public void ShowDialog(Dialogs.BaseDialogModel dlg)
 {
     Dialog = dlg;
     Dialog.MyVisibility = Visibility.Visible;
 }