public IssoViewActivity(int cIsso)
        {
            _cIsso = cIsso;
            InitializeComponent();
            BindingContext = this;
            // Инициализация заголовка
            Title = $"ИССО №{cIsso}";
            // Заполняем общую информацию по ИССО
            var info = _connection.Query <I_ISSO>("select * from I_ISSO where C_ISSO=?", cIsso).ToList()[0];

            var addNewOtc = new ToolbarItem
            {
                Command  = new Command((sender) => AddNewRating()),
                Icon     = CommonStaffUtils.GetFilePath("new_rem_light.png") /*String.Format("{0}{1}", Device.OnPlatform("Icons/", "", "Assets/Icons/"), "new_rem_light.png")*/,
                Priority = 0,
                Order    = ToolbarItemOrder.Primary
            };

            ToolbarItems.Add(addNewOtc);
            _issoLatitude            = info.LATITUDE;
            _issoLongitude           = info.LONGITUDE;
            textViewDescription.Text = info.FULLNAME;
            _length = info.LENGTH;
            if (info.N_OTC_EXP != null)
            {
                _expertRating = $"Экспертная оценка технического состояния: {info.N_OTC_EXP}\n";
            }
            status.Text      = "Расстояние до объекта, м: \nПогрешность GPS, м:";
            _currentLatitude = 0; _currentLongitude = 0;
            RequestLocationUpdates();
            //NewRefreshRatings();

            // Убираем сепаратор в iOS
            issoLVHistory.SeparatorVisibility = Device.RuntimePlatform == Device.Android ? SeparatorVisibility.Default : SeparatorVisibility.None;
        }
        public void InitDefectTree(int cIsso)
        {
            _cIsso = cIsso;
            RefreshDefectsList();

            DefectFilterItem = new ToolbarItem
            {
                Command  = new Command((sender) => ShowDefectFilterPage()),
                Icon     = CommonStaffUtils.GetFilePath("filter_dark.png"),
                Priority = 1,
                Order    = ToolbarItemOrder.Primary
            };

            // Раскомментить потом

            AddDefect = new ToolbarItem
            {
                Command  = new Command((sender) => AddDefectContentPage()),
                Icon     = CommonStaffUtils.GetFilePath("add.png"),
                Priority = 0,
                Order    = ToolbarItemOrder.Primary
            };

            MessagingCenter.Subscribe <string>(this, "DefectAdded", delegate { RefreshDefectsList(); });
        }
Exemple #3
0
 private void Current_PositionChanged(object sender, PositionEventArgs e)
 {
     MyPosition           = e.Position;
     CurrentErrorLbl.Text = $"{e.Position.Accuracy:F1} м.";
     if (e.Position.Accuracy < Accuracy)
     {
         EditStartPointButton.Image = new FileImageSource()
         {
             File = CommonStaffUtils.GetFilePath("define_location_light.png")
         };
         EditEndPointButton.Image = new FileImageSource()
         {
             File = CommonStaffUtils.GetFilePath("define_location_light.png")
         };
     }
     else
     {
         EditStartPointButton.Image = new FileImageSource()
         {
             File = CommonStaffUtils.GetFilePath("no_location_light.png")
         };
         EditEndPointButton.Image = new FileImageSource()
         {
             File = CommonStaffUtils.GetFilePath("no_location_light.png")
         };
     }
 }
        private void IssoLVHistory_ItemTapped(object sender, ItemTappedEventArgs e)
        {
            var          index = ((ObservableCollection <TableRow>)issoLVHistory.ItemsSource).IndexOf(e.Item as TableRow);
            var          table = _connection.Query <RATING>("select * from RATING where C_ISSO=? and RATINGDATE=?", _cIsso, _rows[index].DateMonth).ToList()[0];
            AddNewRating page;

            if (table.SYNC)
            {
                page = new AddNewRating(_cIsso, _currentRating, table.CURRENTRATING, TypeNewRating.IsPreviewed, _currentPosition, table.RATINGDATE, false);
            }
            else
            {
                bool canAddPhotos = false;
                if (_currentPosition != null)
                {
                    double distance = CommonStaffUtils.GetDistance(_issoLatitude, _issoLongitude, _currentPosition.Latitude, _currentPosition.Longitude, _length);
                    if (distance < 100 + _currentPosition.Accuracy)
                    {
                        canAddPhotos = true;
                    }
                }
                page = new AddNewRating(_cIsso, _currentRating, table.CURRENTRATING, TypeNewRating.IsEditable, _currentPosition, table.RATINGDATE, canAddPhotos);
            }
            Navigation.PushAsync(page);
            ((ListView)sender).SelectedItem = null;
        }
Exemple #5
0
        private void SelectedListViewPopupPage_SaveChanges(object sender, EventArgs e)
        {
            var newRoad = (sender as string);

            switch (newRoad)
            {
            case "[Все]":
                FilterBarItem.Icon = new FileImageSource()
                {
                    File = CommonStaffUtils.GetFilePath("filter_dark.png")
                };
                FilterBarItem.Text = "Фильтр не выбран";
                break;

            case "Отмена":
            case null:
                return;

            default:
                FilterBarItem.Icon = new FileImageSource()
                {
                    File = CommonStaffUtils.GetFilePath("filter_enable_light.png")
                };
                FilterBarItem.Text = $"Фильтр: {newRoad}";
                break;
            }
            SelectedRoad         = newRoad;
            Issos                = BindIssos();
            IssoList.ItemsSource = Issos;
            //DependencyService.Get<IMessage>().ShortAlert(String.Format("Выбран фильтр по дороге: {0}", new_road));
        }
        /// <summary>
        /// Метод получения текущих координат
        /// </summary>
        public async void RequestLocationUpdates()
        {
            var hasPermission = await CommonStaffUtils.CheckPermissions(Permission.Location);

            if (!hasPermission)
            {
                return;
            }
            CrossGeolocator.Current.PositionChanged += Current_PositionChanged;
            CrossGeolocator.Current.PositionError   += Current_PositionError;
            await CrossGeolocator.Current.StartListeningAsync(TimeSpan.FromSeconds(1), 5);
        }
        public PDFContentView(int cIsso, int n)
        {
            InitializeComponent();
            Title = $"ИССО №{cIsso}. Просмотр схемы";


            using (var connection = new SqliteConnection(ConnectionClass.NewDatabasePath))
            {
                try
                {
                    var command = connection.CreateCommand();
                    command.CommandText =
                        $"select * from I_SXEMA where C_ISSO={cIsso} and N={n} and SXEMA is not null order by N";
                    command.CommandTimeout = 30;
                    command.CommandType    = CommandType.Text;
                    connection.Open();
                    using (var datareader = command.ExecuteReader())
                    {
                        if (datareader.HasRows)
                        {
                            datareader.Read();
                            // Берем данные по фотографии
                            var photo = Convert.FromBase64String(datareader.GetString(datareader.GetOrdinal("SXEMA")));
                            // Записываем файл в папку
                            var newPath =
                                $"{ConnectionClass.PathToSchemes}/{CommonStaffUtils.RandomNumber(1, 9999999)}.pdf";
                            if (!Directory.Exists(ConnectionClass.PathToSchemes))
                            {
                                Directory.CreateDirectory(ConnectionClass.PathToSchemes);
                            }
                            File.WriteAllBytes(newPath, photo);
                            //if (Device.RuntimePlatform == Device.Android)
                            //    PdfDocView.Source = $"file:///android_asset/pdfjs/web/viewer.html?file={WebUtility.UrlEncode(newPath)}";
                            //else
                            //    PdfDocView.Source = newPath;
                            PdfDocView.Uri = newPath;
                        }
                        datareader.Dispose();
                    }
                    command.Dispose();
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Произошла ошибка в БД: {ex.Message} \nStackTrace: {ex.StackTrace}");
                }
                finally
                {
                    connection.Close();
                }
            }
        }
 private void Current_PositionChanged(object sender, PositionEventArgs e)
 {
     _location         = e.Position;
     _currentLatitude  = e.Position.Latitude;
     _currentLongitude = e.Position.Longitude;
     status.Text       = $"Погрешность GPS, м: {e.Position.Accuracy}";
     imgStatus.Source  = e.Position.Accuracy < _accuracy
             ? new FileImageSource()
     {
         File = CommonStaffUtils.GetFilePath("marker_noway.png")
     }
             : new FileImageSource()
     {
         File = CommonStaffUtils.GetFilePath("marker_ahead.png")
     };
 }
 /// <summary>
 /// Конструктор
 /// </summary>
 /// <param name="cIsso"></param>
 /// <param name="rootNode"></param>
 /// <param name="currentLevel"></param>
 /// <param name="visibleMode"></param>
 public AddIssoDefectContentPageList(int cIsso, Ais7IssoDefectsTreeNode2 rootNode    = null,
                                     Ais7IssoDefectsTreeNode currentLevel            = null,
                                     Ais7IssoDefectsTreeNode.VisibleMode visibleMode = Ais7IssoDefectsTreeNode.VisibleMode.ExistConstructions)
 {
     InitializeComponent();
     Title                 = $"ИССО №{cIsso}: Добавление дефекта.";
     CIsso                 = cIsso;
     CurrentLevel          = currentLevel;
     RootNode              = rootNode;
     VisibilityMode        = visibleMode;
     ChangeDefectView.Icon = new FileImageSource
     {
         File = CommonStaffUtils.GetFilePath(visibleMode == Ais7IssoDefectsTreeNode.VisibleMode.AllContructions
                                 ? "elements_tree_full.png"
                                 : "elements_tree.png")
     };
 }
Exemple #10
0
 public MasterDetailPage1MasterViewModel()
 {
     MenuItems = new ObservableCollection <MasterDetailPage1MenuItem>(new[]
     {
         new MasterDetailPage1MenuItem {
             Id = 0, Title = "Автовыбор", Img = new FileImageSource {
                 File = CommonStaffUtils.GetFilePath("autoselect_light.png")
             }, TargetType = typeof(MapsActivity)
         },
         new MasterDetailPage1MenuItem {
             Id = 1, Title = "Синхронизация", Img = new FileImageSource {
                 File = CommonStaffUtils.GetFilePath("synchronize_light.png")
             }, TargetType = typeof(CommonClassesLibrary.Syncronization)
         },
         new MasterDetailPage1MenuItem {
             Id = 2, Title = "Настройки", Img = new FileImageSource {
                 File = CommonStaffUtils.GetFilePath("settings_light.png")
             }, TargetType = typeof(SettingsActivity)
         }
     });
 }
Exemple #11
0
        public MasterDetailPage1Master()
        {
            InitializeComponent();

            BindingContext = new MasterDetailPage1MasterViewModel();
            ListView       = MenuItemsListView;
            if (App.Current.Properties.TryGetValue("user", out object user))
            {
                LabelUser.Text = "Пользователь: " + user;
            }

            SupportImg.Source = new FileImageSource()
            {
                File = CommonStaffUtils.GetFilePath("support_light.png")                                         /*String.Format("{0}{1}", Device.OnPlatform("Icons/", "", "Assets/Icons/"), "support_light.png")*/
            };
            SupportBtn.GestureRecognizers.Add(new TapGestureRecognizer()
            {
                Command = new Command(() => OpenSupportSite())
            });

            OrientationChanged();
        }
        public MasterDetailPage1Master()
        {
            InitializeComponent();

            BindingContext = new MasterDetailPage1MasterViewModel();
            ListView       = MenuItemsListView;
            if (Application.Current.Properties.TryGetValue("user", out var user))
            {
                LabelUser.Text = "Пользователь: " + user;
            }

            SupportImg.Source = new FileImageSource()
            {
                File = CommonStaffUtils.GetFilePath("support_light.png")
            };
            SupportBtn.GestureRecognizers.Add(new TapGestureRecognizer()
            {
                Command = new Command(OpenSupportSite)
            });
            OrientationChanged();

            ListView.ItemSelected += ListView_ItemSelected;
        }
        private void ChangeDefectView_Clicked(object sender, EventArgs e)
        {
            switch (VisibilityMode)
            {
            case Ais7IssoDefectsTreeNode.VisibleMode.ExistConstructions:
                VisibilityMode        = Ais7IssoDefectsTreeNode.VisibleMode.AllContructions;
                ChangeDefectView.Icon = new FileImageSource {
                    File = CommonStaffUtils.GetFilePath("elements_tree_full.png")
                };
                break;

            case Ais7IssoDefectsTreeNode.VisibleMode.AllContructions:
                VisibilityMode        = Ais7IssoDefectsTreeNode.VisibleMode.ExistConstructions;
                ChangeDefectView.Icon = new FileImageSource {
                    File = CommonStaffUtils.GetFilePath("elements_tree.png")
                };
                break;

            case Ais7IssoDefectsTreeNode.VisibleMode.All:
                break;
            }
            InitTreeDefect();
        }
        private bool CheckGps()
        {
            if (_currentPosition == null)
            {
                DisplayAlert("", "Нет данных о Вашем местоположении", "OK");
                return(false);
            }
            if (_currentPosition.Accuracy > MaximumAccuracy)
            {
                DisplayAlert("",
                             $"Недопустимая точность положения. Текущая погрешность : {_currentPosition.Accuracy:F1} м.", "OK");
                return(false);
            }

            double dist = CommonStaffUtils.GetDistance(_issoLatitude, _issoLongitude, _currentPosition.Latitude, _currentPosition.Longitude, _length);

            if (dist > (100 + _currentPosition.Accuracy))
            {
                DisplayAlert("", "Вы должны находиться на этом сооружении, чтобы иметь возможность вносить сведения", "OK");
                return(false);
            }
            return(true);
        }
        /// <summary>
        /// Handler при изменении текущих координат
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Current_PositionChanged(object sender, PositionEventArgs e)
        {
            _currentPosition  = e.Position;
            _currentLatitude  = e.Position.Latitude;
            _currentLongitude = e.Position.Longitude;
            status.Text       =
                $"Расстояние до объекта, м: {(Math.Abs(_currentLatitude) < CommonStaffUtils.DoubleTolerance ? "[недоступно]" : $"{CommonStaffUtils.GetDistance(_issoLatitude, _issoLongitude, _currentLatitude, _currentLongitude, _length):F1}")}\nПогрешность GPS, м: {(Math.Abs(_currentLatitude) < CommonStaffUtils.DoubleTolerance ? "[недоступно]" : $"{e.Position.Accuracy:F1}")}";
            var dist = CommonStaffUtils.GetDistance(_issoLatitude, _issoLongitude, _currentLatitude, _currentLongitude, _length);

            imgStatus.Source = dist > (100 + e.Position.Accuracy)
                    ? new FileImageSource
            {
                File =
                    CommonStaffUtils.GetFilePath(
                        "marker_noway.png")                     /*String.Format("{0}{1}", Device.OnPlatform("Icons/", "", "Assets/Icons/"), "marker_noway.png")*/
            }
                    : new FileImageSource()
            {
                File =
                    CommonStaffUtils.GetFilePath(
                        "marker_ahead.png")                     /*String.Format("{0}{1}", Device.OnPlatform("Icons/", "", "Assets/Icons/"), "marker_ahead.png")*/
            };
        }
Exemple #16
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(); });
            });
        }
Exemple #17
0
        public EditCoordsContentPage(int cIsso)
        {
            InitializeComponent();
            CIsso = cIsso;
            Title = "АИС ИССО-IX. Изменение геокоординат.";
            MyMap = new Map
            {
                VerticalOptions   = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand
            };
            ForMap.Children.Add(MyMap);

            using (var connection = new SqliteConnection(ConnectionClass.NewDatabasePath))
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandText    = $"select * from V_ISSO where C_ISSO={cIsso}";
                    command.CommandTimeout = 30;
                    command.CommandType    = System.Data.CommandType.Text;
                    connection.Open();
                    using (var datareader = command.ExecuteReader())
                    {
                        if (datareader.HasRows)
                        {
                            while (datareader.Read())
                            {
                                StartGeo = new GeoCoords(Convert.ToDouble(datareader["P1_LATITUDE"]), Convert.ToDouble(datareader["P1_LONGITUDE"]));
                                EndGeo   = new GeoCoords(Convert.ToDouble(datareader["P2_LATITUDE"]), Convert.ToDouble(datareader["P2_LONGITUDE"]));
                            }
                        }
                        datareader.Close();
                    }
                }
                connection.Close();
            }

            CurrentISSOLength.Text =
                $"{(GeoCodeCalc.CalcDistance(StartGeo.Latitude, StartGeo.Longitude, EndGeo.Latitude, EndGeo.Longitude) * 1000):F1} м.";
            if (StartGeo != null && EndGeo != null)
            {
                CenterMap(new List <GeoCoords> {
                    StartGeo, EndGeo
                });
                SetupPins(StartGeo, EndGeo);
            }
            else if (MyPosition != null)
            {
                CenterMap(new List <GeoCoords> {
                    new GeoCoords(MyPosition.Latitude, MyPosition.Longitude)
                });
            }
            // Инициализация кнопки центрирования карты
            Btn_Follow.Image = new FileImageSource()
            {
                File = CommonStaffUtils.GetFilePath("define_location_dark.png")                                                    /*String.Format("{0}{1}", Device.OnPlatform("Icons/", "", "Assets/Icons/"), "free_location_dark.png")*/
            };
            Btn_Follow.Clicked += (s, e) =>
            {
                var listIssos = new List <GeoCoords>();
                if (StartGeo != null && EndGeo != null)
                {
                    listIssos.Add(StartGeo);
                    listIssos.Add(EndGeo);
                }
                else if (MyPosition != null)
                {
                    listIssos.Add(new GeoCoords(MyPosition.Latitude, MyPosition.Longitude));
                }
                CenterMap(listIssos);
            };

            // Инициализация кнопки выбора спутников
            Btn_Satellite.Image = TypesMapImgLight[0];

            EditIssoLocations();

            EditStartPointButton.Image = new FileImageSource {
                File = CommonStaffUtils.GetFilePath("no_location_light.png")
            };
            EditEndPointButton.Image = new FileImageSource {
                File = CommonStaffUtils.GetFilePath("no_location_light.png")
            };

            EditStartPointButton.Clicked += (s, e) => { EditPointButton_Clicked(s, e, true); };
            EditEndPointButton.Clicked   += (s, e) => { EditPointButton_Clicked(s, e, false); };
        }
Exemple #18
0
        private void AddThumbnailsAsync(int cIsso)
        {
            // Вытаскиваем информацию
            Task.Factory.StartNew(() =>
            {
                var pathToDir = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/ISSO-I/";
                // Чистим предыдущие фотки
                if (Directory.Exists(pathToDir))
                {
                    DependencyService.Get <ILocalFileProvider>().DeleteFilesFromDir(pathToDir);
                }
                using (var connection = new SqliteConnection(ConnectionClass.NewDatabasePath))
                {
                    try
                    {
                        _dataInformation    = new List <DataInformation>();
                        var command         = connection.CreateCommand();
                        command.CommandText =
                            $"select * from I_SXEMA where C_ISSO={cIsso} and SXEMA 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("PREVIEW"))),
                                        CommonStaffUtils.StandardImageWidth, CommonStaffUtils.StandardImageHeight);
                                    var date = datareader["SXEMA_DATE"] != DBNull.Value
                                                                                ? datareader.GetInt64(datareader.GetOrdinal("SXEMA_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();
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine($"Произошла ошибка в БД: \n{ex.Message} \nStackTrace: {ex.StackTrace}");
                    }
                    finally
                    {
                        connection.Close();
                    }
                }

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


                // Добавляем данные в StackLayout
                //foreach (DataInformation information in dataInformation)
                //{
                //    // Создаем ContentView
                //    StackLayout contentViewPhoto = new StackLayout
                //    {
                //        VerticalOptions = LayoutOptions.FillAndExpand,
                //        HorizontalOptions = LayoutOptions.FillAndExpand,
                //        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}", information.Image_source)
                //    };
                //    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) =>
                //    {
                //        ShowPDF(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(() => { thumb_container.Children.Add(contentViewPhoto); });
                //}
                //Device.BeginInvokeOnMainThread(() => { OnSizeAllocated(App.Current.MainPage.Width, scroll_thumb.Height); Navigation.PopPopupAsync(); });
            });
        }
        /// <summary>
        /// Конструктор создания новой записи текущего состояния
        /// </summary>
        /// <param name="cIsso">Номер ИССО</param>
        /// <param name="allRating">Итоговый рейтинг</param>
        /// <param name="lastRating">Последний рейтинг</param>
        /// <param name="typeOfRating">Тип рейтинга</param>
        /// <param name="geoPosition">Последние координаты</param>
        /// <param name="dateMonth">Дата</param>
        /// <param name="canAddPhotos"></param>
        public AddNewRating(int cIsso, int allRating, int lastRating, TypeNewRating typeOfRating, Position geoPosition, long dateMonth, bool canAddPhotos)
        {
            _cIsso        = cIsso;
            _lastRating   = lastRating;
            _geoPosition  = geoPosition;
            _typeOfRating = typeOfRating;
            _dateMonth    = dateMonth;
            // Добавление кнопок меню
            //if(TypeOfRating != TypeNewRating.IsPreviewed)
            //{
            //    ToolbarItem ItemSave = new ToolbarItem()
            //    {
            //        Command = new Command(() => SaveToDatabase()),
            //        Icon = String.Format("{0}{1}", Device.OnPlatform("Icons/", "", "Assets/Icons/"), "save_light.png"),
            //        Priority = 1,
            //        Order = ToolbarItemOrder.Primary
            //    };
            //    ToolbarItems.Add(ItemSave);
            //}
            //ItemCamera.Command = new Command(() => TakePicture());


            // Настройка выпадающего списка
            // Если суммарный рейтинг меньше 1, то убираем степень улучшения

            InitializeComponent();
            // Обработка нажатия "назад"
            CustomBackButtonAction += SaveToDatabase;
            if (!canAddPhotos)
            {
                AddPhotoButton.IsEnabled = false;
                AddPhotoButton.IsVisible = false;
            }

            foreach (var otc in OtcVariables.Values)
            {
                pick_otc.Items.Add(otc);
            }
            pick_otc.Title = "Выберите степень ухудшения/улучшения:";
            pick_otc.SelectedIndexChanged += Pick_otc_SelectedIndexChanged;
            img_otc.Source = Drawables[Otc.NotChanged];
            // если не можем редактировать, то получаем сведения по геолокации, и соответственно последнее значение рейтинга
            // иначе получаем предыдущий рейтинг путем вычитания последнего значения из общего рейтинга
            switch (typeOfRating)
            {
            case TypeNewRating.IsNew:
                _allRating = allRating;
                if (_allRating > -1)
                {
                    OtcVariables.Remove(Otc.Improved);
                    Drawables.Remove(Otc.Improved);
                    pick_otc.Items.Remove("Улучшение");
                }
                Title = "ИССО №" + cIsso + ". Добавление рейтинга";
                //Comments.Text = "";
                pick_otc.SelectedIndex = 0;
                break;

            case TypeNewRating.IsPreviewed:
                _allRating = allRating - lastRating;
                if (_allRating > -1)
                {
                    OtcVariables.Remove(Otc.Improved);
                    Drawables.Remove(Otc.Improved);
                    pick_otc.Items.Remove("Улучшение");
                }
                Title = "ИССО №" + cIsso + ". Просмотр оценки";
                BindContent();
                // отключение всех контролов
                switchOTC.IsEnabled = false;
                SeekBar.IsEnabled   = false;
                pick_otc.IsEnabled  = false;
                Comments.IsEnabled  = false;
                break;

            case TypeNewRating.IsEditable:
                _allRating = allRating - lastRating;
                if (_allRating > -1)
                {
                    OtcVariables.Remove(Otc.Improved);
                    Drawables.Remove(Otc.Improved);
                    pick_otc.Items.Remove("Улучшение");
                }
                Title = "ИССО №" + cIsso + ". Редактирование оценки";
                BindContent();
                break;
            }

            _isLaunched = true;
            ListViewPhotos.IsVisible = _photos.Count > 0;
            // Тестовый набор для фотографий
            //ObservableCollection<PhotoInfo> photos = new ObservableCollection<PhotoInfo>();
            //photos.Add(new PhotoInfo(new FileImageSource() { File = "launcher.png" }, "Здесь есть коммент"));
            //ListViewPhotos.ItemsSource = photos;
            if (typeOfRating == TypeNewRating.IsPreviewed)
            {
                AddPhotoButton.IsEnabled = false;
                AddPhotoButton.IsVisible = false;
            }
            AddPhotoButton.Image = new FileImageSource()
            {
                File = CommonStaffUtils.GetFilePath("camera_light.png")                                            /*String.Format("{0}{1}", Device.OnPlatform("Icons/", "", "Assets/Icons/"), "camera_light.png")*/
            };

            ListViewPhotos.SeparatorVisibility = Device.RuntimePlatform == Device.Android ? SeparatorVisibility.Default : SeparatorVisibility.None;
        }
Exemple #20
0
        private void SetupPins(GeoCoords start, GeoCoords end)
        {
            MyMap.Pins.Clear();

            if (start != null)
            {
                var startPin = new Pin
                {
                    Position = new Xamarin.Forms.GoogleMaps.Position(start.Latitude, start.Longitude),
                    Anchor   = new Point(0.5, 1.0),
                    Label    = "Начало ИССО",
                    Icon     = Device.RuntimePlatform.Equals(Device.Android)
                                                ? BitmapDescriptorFactory.FromBundle("marker_ahead.png")
                                                : BitmapDescriptorFactory.FromView(new ContentView
                    {
                        WidthRequest  = 40,
                        HeightRequest = 40,
                        Scale         = 1,
                        Content       = new Image
                        {
                            Source = new FileImageSource()
                            {
                                File =
                                    CommonStaffUtils.GetFilePath(
                                        "marker_ahead.png")                                                 /*String.Format("{0}{1}", Device.OnPlatform("Icons/", "Assets/", "Assets/Icons/"), "marker_far.png")*/
                            },
                            Aspect        = Aspect.AspectFit,
                            WidthRequest  = 40,
                            HeightRequest = 40
                        }
                    })
                };
                MyMap.Pins.Add(startPin);
            }

            if (end != null)
            {
                var endPin = new Pin
                {
                    Position = new Xamarin.Forms.GoogleMaps.Position(end.Latitude, end.Longitude),
                    Anchor   = new Point(0.5, 1.0),
                    Label    = "Конец ИССО",
                    Icon     = Device.RuntimePlatform.Equals(Device.Android)
                                                ? BitmapDescriptorFactory.FromBundle("marker_behind.png")
                                                : BitmapDescriptorFactory.FromView(new ContentView
                    {
                        WidthRequest  = 40,
                        HeightRequest = 40,
                        Scale         = 1,
                        Content       = new Image
                        {
                            Source = new FileImageSource()
                            {
                                File =
                                    CommonStaffUtils.GetFilePath(
                                        "marker_behind.png")                                                 /*String.Format("{0}{1}", Device.OnPlatform("Icons/", "Assets/", "Assets/Icons/"), "marker_far.png")*/
                            },
                            Aspect        = Aspect.AspectFit,
                            WidthRequest  = 40,
                            HeightRequest = 40
                        }
                    })
                };
                MyMap.Pins.Add(endPin);
            }


            GeoStartPointImage.Source = new FileImageSource {
                File = CommonStaffUtils.GetFilePath("marker_ahead.png")
            };
            GeoEndPointImage.Source = new FileImageSource {
                File = CommonStaffUtils.GetFilePath("marker_behind.png")
            };

            GeoStartPointImage.GestureRecognizers.Add(new TapGestureRecognizer {
                Command = new Command(() => { MoveCamera(StartGeo); })
            });
            GeoEndPointImage.GestureRecognizers.Add(new TapGestureRecognizer {
                Command = new Command(() => { MoveCamera(EndGeo); })
            });
        }