Example #1
0
        public void InitTreeView(int cIsso)
        {
            var page = new LoadingPopupPage("Идет построение дерева...", true);

            Navigation.PushPopupAsync(page, false);
            Task.Factory.StartNew(() =>
            {
                var infoRows = DoSqlCount(cIsso);
                _viewModel   = new TreeViewModel(infoRows, cIsso);
                //TreeViewModel.navigation = this.Navigation;
                NodeCreationFactory = () => new TreeNodeView
                {
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions   = LayoutOptions.Fill,
                };
                Device.BeginInvokeOnMainThread(() =>
                {
                    HeaderCreationFactory = () => new DemoTreeCardView
                    {
                        HorizontalOptions = LayoutOptions.FillAndExpand,
                        VerticalOptions   = LayoutOptions.Start
                    };
                    BindingContext = _viewModel.Tree;
                    Navigation.PopPopupAsync();
                });
            });
        }
        private async void ManglerListView_ItemTappedAsync(object sender, ItemTappedEventArgs e)
        {
            var loadingPage = new LoadingPopupPage();
            var vm          = BindingContext as ViewModels.MainViewModel;
            var mangel      = e.Item as Mangel;

            if (await DisplayAlert("Slet mangel", "Vil du slette denne mangel?", "Slet", "Annuller"))
            {
                await Navigation.PushPopupAsync(loadingPage);

                if (await vm.DeleteMangelAsync(mangel))
                {
                    await Task.Delay(200);

                    await Navigation.RemovePopupPageAsync(loadingPage);

                    await Navigation.PushPopupAsync(new FjernMangelSuccessPopupPage());
                }
                else
                {
                    await Task.Delay(200);

                    await Navigation.RemovePopupPageAsync(loadingPage);

                    await Navigation.PushPopupAsync(new FjernMangelFailurePopupPage());
                }
            }
        }
        public DefectForCGrConstrPage(int cIsso, Ais7IssoDefectsTreeNode parent, IReadOnlyCollection <Ais7IssoDefectsTreeNode> advancedDefects)
        {
            InitializeComponent();
            Title = $"ИССО №{cIsso}: Добавление дефекта. {parent.NGrConstr}";
            var page = new LoadingPopupPage("Идет подбор дефектов...", true);

            Navigation.PushPopupAsync(page, false);
            Task.Factory.StartNew(() =>
            {
                var scrollView = new ScrollView()
                {
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions   = LayoutOptions.FillAndExpand,
                    Orientation       = ScrollOrientation.Vertical
                };
                var stackLayout = new StackLayout
                {
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions   = LayoutOptions.FillAndExpand,
                    Orientation       = StackOrientation.Vertical
                };
                scrollView.Content = stackLayout;
                var mainDefect     = new DefectTreeView(cIsso, parent, true);
                stackLayout.Children.Add(mainDefect);
                foreach (var child in advancedDefects)
                {
                    stackLayout.Children.Add(new DefectTreeView(cIsso, child, false));
                }
                Device.BeginInvokeOnMainThread(() =>
                {
                    Content = scrollView;
                    Navigation.PopPopupAsync();
                });
            });
        }
Example #4
0
        public async Task <PopupPage> OpenLoadingPopup()
        {
            LoadingPopupPage _loadingPopup = new LoadingPopupPage();
            await PopupNavigation.Instance.PushAsync(_loadingPopup, true);

            return(_loadingPopup);
        }
Example #5
0
        public QualityParametersTreeView(CreateDefectModel defectModel)
        {
            InitializeComponent();
            var page = new LoadingPopupPage("Пожалуйста, подождите...", true);

            Navigation.PushPopupAsync(page, false);
            Task.Factory.StartNew(() =>
            {
                var stackLayout = new StackLayout
                {
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    VerticalOptions   = LayoutOptions.FillAndExpand,
                    Orientation       = StackOrientation.Vertical
                };
                TreeStackLayout.Content = stackLayout;
                var mainDefect          = new ParamTreeView(defectModel);
                stackLayout.Children.Add(mainDefect);
                //foreach (var child in defectModel.DefectParameters)
                //	stackLayout.Children.Add(new DefectTreeView(cIsso, child, false));
                Device.BeginInvokeOnMainThread(() =>
                {
                    Navigation.PopPopupAsync();
                    BindingContext = new QualityParametersTreeViewModel();
                });
            });
        }
        public async void RefreshDefectsList(bool needToObtainFilter = true)
        {
            var page = new LoadingPopupPage("Подождите, идет загрузка...", true);
            await Navigation.PushPopupAsync(page, false);

            await Task.Factory.StartNew(() =>
            {
                DefectTreeNode = BuildTree.GetDefectTree();
                _defectsList   = CreateDefectList(_cIsso);
                if (_defectsList.Count <= 0)
                {
                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        await Navigation.PopPopupAsync();
                        Content = new Label
                        {
                            VerticalOptions   = LayoutOptions.Center,
                            HorizontalOptions = LayoutOptions.Center,
                            Text = "Дефекты на данном сооружении отсутствуют."
                        };
                    });
                    return;
                }
                if (needToObtainFilter)
                {
                    CreateFilterAttributes(_defectsList);
                }
                Device.BeginInvokeOnMainThread(async() => { DrawDefectTable(_defectsList); await Navigation.PopPopupAsync(); });
            });
        }
Example #7
0
        public void Initialize(int cIsso)
        {
            _cIsso = cIsso;
            var page = new LoadingPopupPage("Подождите, идет загрузка схем...", true);

            Navigation.PushPopupAsync(page, false);
            AddThumbnailsAsync(cIsso);
        }
Example #8
0
        public static async Task <LoadingPopupPage> StartLoading(this ILayout page)
        {
            var loader = new LoadingPopupPage();

            _cachedLoader.Add(loader);
            await PopupNavigation.Instance.PushAsync(loader, true);

            return(loader);
        }
Example #9
0
 /// <summary>
 ///     Close popup
 /// </summary>
 /// <param name="page"></param>
 public static async void EndLoading(this LoadingPopupPage page)
 {
     if (_cachedLoader.IndexOf(page) < 0)
     {
         return;
     }
     _cachedLoader.Remove(page);
     await PopupNavigation.Instance.RemovePageAsync(page, true);
 }
        protected override void OnAppearing()
        {
            base.OnAppearing();


            // Если у нас RootNode ещё не строился, то вызываем buildTree в отдельном потоке, иначе просто строим список
            if (RootNode != null)
            {
                InitTreeDefect();
            }
            else
            {
                var popupPage = new LoadingPopupPage("Идет построение дерева дефектов...", true);
                Navigation.PushPopupAsync(popupPage);
                Task.Factory.StartNew(() =>
                {
                    RootNode = BuildTree();
                    Device.BeginInvokeOnMainThread(() => { InitTreeDefect(); Navigation.PopPopupAsync(); });
                });
            }

            const string textStart = "Путь до текущей группы конструкций: ";

            // Путь в дереве дефектов
            // Если это родительская нода
            if (CurrentLevel?.ParentNode != null)
            {
                var nameBuilder = new StringBuilder(CurrentLevel.NGrConstr);
                var tempNode    = CurrentLevel;
                // Пока не дошли до рутовой ноды
                while (tempNode.ParentNode != null)
                {
                    tempNode = tempNode.ParentNode;
                    // не записываем "Общие данные"
                    if (tempNode.ParentNode != null)
                    {
                        // записываем в начало
                        nameBuilder.Insert(0, $"{tempNode.NGrConstr}/");
                    }
                }
                TreeNodeLevelLabel.Text = $"{textStart}/{nameBuilder}";
            }
            // Иначе мы убираем с экрана этот label
            else
            {
                TreeNodeLevelLabel.Text = $"{textStart}/";
                //TreeNodeLevelLabel.IsVisible = false;
            }
        }
Example #11
0
        private async void MicrophonePressed(object sender, EventArgs e)
        {
            var speechStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Speech);

            var microStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Microphone);

            if (speechStatus != PermissionStatus.Granted || microStatus != PermissionStatus.Granted)
            {
                var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Speech, Permission.Microphone);

                microStatus  = results[Permission.Microphone];
                speechStatus = results[Permission.Speech];
            }

            if (speechStatus == PermissionStatus.Granted && microStatus == PermissionStatus.Granted)
            {
                //listener = CrossSpeechRecognition.Current.ContinuousDictation().Subscribe(
                //    phrase =>
                //    {
                //        EntryComment.Text += phrase;
                //    },
                //    completed =>
                //    {
                //        listener.Dispose();
                //    });
                //CrossSpeechRecognition.Current.ContinuousDictation().Subscribe(phrase => { EntryComment.Text += phrase; },
                //    () => { CrossSpeechRecognition.Current.ContinuousDictation().Subscribe().Dispose(); });
                CrossSpeechRecognition.Current.ListenUntilPause().Subscribe(phrase => { EntryComment.Text += phrase; }, async() => { Animate_Button(false); await Navigation.PopPopupAsync(); });
                var loadingPopupPage = new LoadingPopupPage("Пожалуйста, говорите!", true);
                Animate_Button(true);
                await Navigation.PushPopupAsync(loadingPopupPage);
            }
            else
            {
                var alertPage = new AlertPopupPage(true, "Распознавание речи невозможно, т.к. недостаточно разрешений для этого.");
                await Navigation.PushPopupAsync(new CommonPopupPage(alertPage, "Недостаточно разрешений"));

                //await DisplayAlert("Недостаточно разрешений", "Распознавание речи невозможно, т.к. недостаточно разрешений для этого.", "OK");
                //On iOS you may want to send your user to the settings screen.
                //CrossPermissions.Current.OpenAppSettings();
            }
        }
        /// <summary>
        /// Обработчик нажатия кнопки микрофона
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Microphone_Clicked(object sender, EventArgs e)
        {
            // Проверка доступности разрешений на применение действий
            var speechStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Speech);

            var microStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Microphone);

            if (speechStatus != PermissionStatus.Granted || microStatus != PermissionStatus.Granted)
            {
                // В случае с отсутствием таковых идем запрашивать такие разрешения у пользователя
                var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Speech, Permission.Microphone);

                microStatus  = results[Permission.Microphone];
                speechStatus = results[Permission.Speech];
            }

            // После чего ещё раз проверяем доступность разрешений
            if (speechStatus == PermissionStatus.Granted && microStatus == PermissionStatus.Granted)
            {
                // Инициализация API преобразования речи в текст
                CrossSpeechRecognition.Current.ListenUntilPause().Subscribe(phrase => { filter_entry.Text += phrase; }, async() => { Animate_Button(microphone_button, false); await Navigation.PopPopupAsync(); });
                var loadingPopupPage = new LoadingPopupPage("Пожалуйста, говорите!", true);
                Animate_Button(microphone_button, true);
                await Navigation.PushPopupAsync(loadingPopupPage);
            }
            else
            {
                // Иначе говорим, что разерешений таких нет, увы и ах
                await Navigation.PushPopupAsync(new CommonPopupPage(
                                                    new AlertPopupPage(true, "Распознавание речи невозможно, т.к. недостаточно разрешений для этого."),
                                                    "Недостаточно разрешений"));

                //await Application.Current.MainPage.DisplayAlert("Недостаточно разрешений", "Распознавание речи невозможно, т.к. недостаточно разрешений для этого.", "OK");
                //On iOS you may want to send your user to the settings screen.
                //CrossPermissions.Current.OpenAppSettings();
            }
        }
Example #13
0
        private void ButtonForward_OnClicked(object sender, EventArgs e)
        {
            // Если дошли до конца и нажали на Добавить дефект, то вызываем окно предупередительное и добавляем собсна
            if (CarouselView.Position == _indexSummary)
            {
                var addPopupPage = new AlertPopupPage(false, "Вы уверены, что хотите добавить новый дефект?", confirmText: "Добавить");
                // При нажатии на Да добавляем и вырубаем окно
                addPopupPage.Confirm += (o, args) =>
                {
                    var popupPage = new LoadingPopupPage("Добавление дефекта в БД...", true);
                    Navigation.PushPopupAsync(popupPage);
                    Task.Factory.StartNew(() =>
                    {
                        if (_vm.AddDefectToDatabase())
                        {
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                DoneWithDefect();
                                Navigation.PopPopupAsync();
                            });
                        }
                        else
                        {
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                DependencyService.Get <IMessage>().ShortAlert("Невозможно создать дефект. Ошибка при добавлении.");
                                Navigation.PopPopupAsync();
                            });
                        }
                    });
                };
                Navigation.PushPopupAsync(new CommonPopupPage(addPopupPage, "Добавление дефекта"));
            }
            // иначе идем дальше
            else
            {
                if (!_interactors[CarouselView.Position] && CarouselView.Position != _indexAdvanced)
                {
                    return;
                }
                CarouselView.Position  += 1;
                ButtonBack.IsVisible    = CarouselView.Position != 0;
                ButtonForward.IsEnabled = _interactors[CarouselView.Position];
                // Если дошли до доп инфы, прописываем поведение кнопок
                if (CarouselView.Position == _indexAdvanced)
                {
                    ButtonForward.Text  = _interactors[_indexAdvanced] ? "Далее" : "Пропустить";
                    ButtonForward.Style = _interactors[_indexAdvanced] ? (Style)Application.Current.Resources["ButtonStandard"]
                                                : (Style)Application.Current.Resources["ButtonStandardCancel"];
                    // для доп инфы всегда можно нажимать
                    ButtonForward.IsEnabled = true;
                }
                // Если же дошли до даты, то прописываем там поведение
                else if (CarouselView.Position == _indexAdvanced + 1)
                {
                    ButtonForward.Text  = "Далее";
                    ButtonForward.Style = _interactors[_indexAdvanced + 1] ? (Style)Application.Current.Resources["ButtonStandard"]
                                                : (Style)Application.Current.Resources["ButtonStandardCancel"];
                }
                // Дошли до конца - прописываем соответствующее поведение
                else if (CarouselView.Position == _indexSummary)
                {
                    ButtonForward.Text  = "Добавить дефект";
                    ButtonForward.Style = (Style)Application.Current.Resources["ButtonStandard"];
                }
                else
                {
                    ButtonForward.Text  = "Далее";
                    ButtonForward.Style = _interactors[CarouselView.Position] ? (Style)Application.Current.Resources["ButtonStandard"]
                                                : (Style)Application.Current.Resources["ButtonStandardCancel"];
                }
            }
            // Навигация по мастеру вперед

            //if (CarouselView.Position == _indexSummary)
            //	ButtonForward.Text = "Добавить дефект";
            //else
            //	ButtonForward.Text = CarouselView.Position == _indexAdvanced ? "Пропустить" : "Далее";
            //ButtonForward.Style = CarouselView.Position == _indexSummary
            //	? (Style)Application.Current.Resources["ButtonStandard"]
            //	: (Style)Application.Current.Resources["ButtonStandardCancel"];
        }
Example #14
0
        private void AddPhotosAsync(int cIsso)
        {
            _dataInformation.Clear();
            var page = new LoadingPopupPage("Подождите, идет загрузка фотографий...", true);

            Navigation.PushPopupAsync(page, false);
            Task.Factory.StartNew(() =>
            {
                // Вытаскиваем информацию
                using (var connection = new SqliteConnection(ConnectionClass.NewDatabasePath))
                {
                    _dataInformation       = new List <DataInformation>();
                    var command            = connection.CreateCommand();
                    command.CommandText    = $"select * from I_FOTO where C_ISSO={cIsso} and FOTO is not null order by N";
                    command.CommandTimeout = 30;
                    command.CommandType    = System.Data.CommandType.Text;
                    connection.Open();
                    using (var datareader = command.ExecuteReader())
                    {
                        if (datareader.HasRows)
                        {
                            while (datareader.Read())
                            {
                                // Берем данные по фотографии
                                var photo = DependencyService.Get <IMediaService>()
                                            .ResizeImage(
                                    Convert.FromBase64String(datareader.GetString(datareader.GetOrdinal("FOTO"))),
                                    CommonStaffUtils.StandardImageWidth, CommonStaffUtils.StandardImageHeight);
                                var date = datareader["FOTO_DATE"] != DBNull.Value ? datareader.GetInt64(datareader.GetOrdinal("FOTO_DATE")) : 0;
                                var info = datareader["TITR"] != DBNull.Value ? datareader.GetString(datareader.GetOrdinal("TITR")) : "";
                                var n    = datareader["N"] != DBNull.Value ? datareader.GetInt32(datareader.GetOrdinal("N")) : 0;

                                var newPath =
                                    $"{Environment.GetFolderPath(Environment.SpecialFolder.Personal)}/ISSO-I/{CommonStaffUtils.RandomNumber(1, 9999999)}";
                                if (!Directory.Exists($"{Environment.GetFolderPath(Environment.SpecialFolder.Personal)}/ISSO-I"))
                                {
                                    Directory.CreateDirectory($"{Environment.GetFolderPath(Environment.SpecialFolder.Personal)}/ISSO-I");
                                }

                                using (var fileStream = new FileStream(newPath, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    fileStream.Write(photo, 0, photo.Length);
                                }

                                _dataInformation.Add(new DataInformation(info, date, photo, newPath, n));
                            }
                        }
                        datareader.Dispose();
                    }
                    command.Dispose();
                    connection.Close();
                }

                Device.BeginInvokeOnMainThread(() =>
                {
                    lv_photos.ItemsSource = _dataInformation;
                    if (_dataInformation.Count <= 0)
                    {
                        Content = new Label
                        {
                            VerticalOptions   = LayoutOptions.Center,
                            HorizontalOptions = LayoutOptions.Center,
                            Text = "Фотографии данного сооружения отсутствуют."
                        };
                    }
                    Navigation.PopPopupAsync();
                });

                //// Добавляем контролы в StackLayout
                //foreach (DataInformation information in Data_Information)
                //{
                //    // Создаем ContentView
                //    StackLayout contentViewPhoto = new StackLayout
                //    {
                //        VerticalOptions = LayoutOptions.Fill,
                //        HorizontalOptions = LayoutOptions.Fill,
                //        Orientation = StackOrientation.Vertical
                //    };
                //    Image image = new Image
                //    {
                //        Margin = new Thickness(10, 10, 10, 0),
                //        VerticalOptions = LayoutOptions.FillAndExpand,
                //        HorizontalOptions = LayoutOptions.FillAndExpand,
                //        Source = ImageSource.FromStream(() => new MemoryStream(information.Array)),
                //        ClassId = String.Format("{0}", Data_Information.IndexOf(information))
                //    };
                //    var date_str = information.Date != 0 ? new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(information.Date).ToString("dd.MM.yyyy") : "";
                //    Label label = new Label
                //    {
                //        VerticalOptions = LayoutOptions.Start,
                //        HorizontalOptions = LayoutOptions.Fill,
                //        VerticalTextAlignment = TextAlignment.Start,
                //        HorizontalTextAlignment = TextAlignment.Center,
                //        Text = !date_str.Equals("") ? String.Format("{0}\n{1}", date_str, information.Info) : information.Info,
                //        Margin = new Thickness(0, 10)
                //    };

                //    var tap = new TapGestureRecognizer();
                //    tap.Tapped += (sender, e) =>
                //    {
                //        ShowPictures(Convert.ToInt32((sender as View).ClassId));
                //    };
                //    image.GestureRecognizers.Add(tap);

                //    BoxView boxView = new BoxView
                //    {
                //        HeightRequest = 1,
                //        Margin = 1,
                //        Opacity = 0.8,
                //        BackgroundColor = Color.FromHex("Accent")
                //    };
                //    // Добавляем в stacklayout наши фотографии с описанием
                //    contentViewPhoto.Children.Add(image);
                //    contentViewPhoto.Children.Add(label);
                //    //contentViewPhoto.Children.Add(boxView);
                //    Device.BeginInvokeOnMainThread(() => { image_container.Children.Add(contentViewPhoto); });
                //}

                // Добавляем данные
                //Device.BeginInvokeOnMainThread(() =>
                //{
                //    int index = 0;
                //    foreach(StackLayout layout in image_container.Children)
                //    {
                //        var date_str = Data_Information[index].Date != 0 ? new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(Data_Information[index].Date).ToString("dd.MM.yyyy") : "";

                //            (layout.Children[0] as Image).Source = ImageSource.FromStream(() => new MemoryStream(Data_Information[index].Array));
                //            (layout.Children[1] as Label).Text = !date_str.Equals("") ? String.Format("{0}\n{1}", date_str, Data_Information[index].Info) : Data_Information[index].Info;
                //        index++;
                //    }
                //});

                //Device.BeginInvokeOnMainThread(() => { OnSizeAllocated(App.Current.MainPage.Width, scroll_view_photo.Height); Navigation.PopPopupAsync(); });
            });
        }